可能没有正确地学习这一点

时间:2014-05-05 16:03:43

标签: format printf

我希望我的回答能够阅读

                1 2 3
Matrix A =      1 2 3
                1 2 3

但它的内容是

Matrix A = 
1 2 3
1 2 3
1 2 3

有谁能告诉我应该如何进行格式化?

public static void IO(int[][] a, int[][] b)
   {
      int i;

      int j;

      System.out.print("Please Enter the Numbers for Matrix A: ");

      for(i=0;i<3;i++)

         for(j=0;j<3;j++)

            a[i][j]=scan.nextInt();

      System.out.println();

      System.out.print("Please Enter The Numbers for Matrix B: ");

      for(i=0;i<3;i++)

         for(j=0;j<3;j++)

            b[i][j]=scan.nextInt();

      System.out.printf("%-1s%n", "Matrix A = ");

      for(i=0;i<3;i++)
      {
         for(j=0;j<3;j++)
         {
            System.out.printf("%5d", a[i][j]);
         }
         System.out.println();
      }
      System.out.printf("%-1s%n", "Matrix B = ");


      for(i=0;i<3;i++)
      {
         for(j=0;j<3;j++)
         {
            System.out.printf("%5d", b[i][j]);
         }
         System.out.println();
      }
   }

我知道这对某些人来说似乎很简单,但我现在只编写了一个学期。非常感谢任何建议!

1 个答案:

答案 0 :(得分:0)

摆脱:

  System.out.printf("%-1s%n", "Matrix A = ");

并将您的循环更改为:

  for(i=0;i<3;i++)
  {
     for(j=0;j<3;j++)
     {
        if(j == 1)
            line_prefix = "Matrix A = ";
        else
            line_prefix = " ";
        System.out.printf("%12.12s%5d", lineprefix, a[i][j]);
     }
     System.out.println();
  }