【问题标题】:How to align String on console output如何在控制台输出上对齐字符串
【发布时间】:2012-10-09 05:52:06
【问题描述】:

我要编写代码:

我写了代码:

public class tables {
    public static void main(String[] args) {
        //int[][] table = new int[12][12];
        String table="";
        for(int i=1; i<13; i++){
            for(int j=1; j<13; j++){
                //table[i-1][j-1] = i*j;
                table+=(i*j)+" ";
            }
            System.out.println(table.trim());
            table="";
        }
    }
}

但问题在于输出格式。我需要以类似矩阵的方式输出,每个数字都格式化为 4 的宽度(数字是右对齐的,并在每行上去掉前导/尾随空格)。我试过 google 但没有找到任何好的解决方案来解决我的问题。谁能帮帮我?

【问题讨论】:

  • @khachik:您能描述一下String.format(%4s", ...) 的工作原理吗? format() 中的第二个参数是什么?

标签: java string console formatter


【解决方案1】:

您可以根据需要使用format() 来格式化您的输出..

    for(int i=1; i<13; i++){
        for(int j=1; j<13; j++){

           System.out.format("%5d", i * j);
        }
        System.out.println();  // To move to the next line.
    }

或者,您也可以使用:-

System.out.print(String.format("%5d", i * j));

代替System.out.format..

以下是%5d如何工作的解释:-

  • 首先,由于我们打印的是整数,我们应该使用%d,它是整数的格式说明符。
  • 5 in %5d 表示您的输出将占用的总宽度。因此,如果您的值为 5,它将被打印为覆盖 5 个空格,如下所示: - ****5
  • %5d 用于右对齐。对于左对齐,您可以使用%-5d。对于值5,这会将您的输出打印为:-5****

【讨论】:

  • 谢谢。有用。您能否在回答中描述%5sformat() 中的工作方式?
  • @MohammadFaisal.. 您可以使用%5d,因为您正在打印整数.. 我将在帖子中解释..
  • @MohammadFaisal : 检查 [javadoc](docs.oracle.com/javase/7/docs/api/java/lang/…, java.lang.Object...) ) 提供指向details的链接
  • @RohitJain:上面的输出是否需要%4s%5s
  • @MohammadFaisal.. 你可以给出任何可以适应你的宽度的值.. 见我的解释.. 如果你使用%4s 表示 12345,它不会适应宽度4..
【解决方案2】:

在我的示例中,数组包含长度不同的字符串,因此我无法排列字符串,并且不同数组的其他字符串在控制台上不匹配。有了不同的概念,我可以安排那些 控制台上的数组我的代码如下。

package arrayformat;

 /**
 *
 * @author Sunil
 */
 public class ArrayFormat {



  /**
  * @param args the command line arguments
  */

  public static void main(String[] args) {

  int[] productId = new int[]  
 {1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,};
   String[] productName= new String[]{"Pepsi","kissan jam","Herbal 
 oil","Garnier man's","Lays chips","biscuits","Bournvita","Cadbury","Parker 
 Vector","Nescafe",};
   String[] productType = new String[]{"Cold Drink","Jam","Oil","Face 
 wash","chips","Biscuits","Health 
 Supplement","Chocolate","Stationary","Coffee",};
    float[] productPrice = new float[]{24,65,30,79,10,20,140,20,150,80,}; 


       int productNameMaxlength=0;
   int productTypeMaxlength=0;



    for (String productName1 : productName) {
        if (productNameMaxlength < productName1.length()) {
            productNameMaxlength = productName1.length();
        }
    }


    for (String productType1 : productType) {
        if (productTypeMaxlength < productType1.length()) {
            productTypeMaxlength = productType1.length();
        }
    }



   for(int i=0;i<productType.length;i++)

   { 
              System.out.print(i);

      System.out.print("\t");

              System.out.print(productId[i]);

              System.out.print("\t");

              System.out.print(productName[i]);

       for(int j=0;j<=productNameMaxlength-productName[i].length
     ();j++)

       {

        System.out.print(" ");

       }

       System.out.print("\t");

       System.out.print(productType[i]);

       for(int j=0;j<=productTypeMaxlength-productType[i].length
    ();j++)

       {
           System.out.print(" ");
       }

               System.out.print("\t");

       System.out.println(productPrice[i]);
          }           
      }

    }
   and output is--
  Sr.No  ID     NAME            TYPE               PRICE
   0    1001    Cadbury         Chocolate           20.0
   1    1002    Parker Vector   Stationary          150.0
   2    1003    Nescafe         Coffee              80.0
   3    1004    kissan jam      Jam                 65.0
   4    1005    Herbal oil      Oil                 30.0
   5    1006    Garnier man's   Face wash           79.0
   6    1007    Lays chips      chips               10.0
   7    1008    biscuits        Biscuits            20.0
   8    1009    Bournvita       Health Supplement   140.0
   9    1010    Pepsi           Cold Drink          24.0

由于我无法回答我的问题,因为阻止提问和回答,所以我引用了我的答案,我觉得这是一种不同的数组格式。

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
  • 由于我无法回答我的问题,因为我无法回答问题并回答问题,所以我引用了我的答案,我觉得这是一种不同的数组格式。
【解决方案3】:

可以使用 System.out.format("","") 方法对输出进行格式化,该方法包含两个输入参数,第一个定义格式样式,第二个定义要打印的值。让我们假设您想要将 n 位值右对齐。您将传递第一个参数“%4d”。

左对齐使用 -ve %-nd

右对齐使用 +ve %nd

 for(int i=1; i<13; i++){
       for(int j=1; j<13; j++){
            System.out.format("%4d", i * j);  //each number formatted to a width of 4 so use %4d in the format method.
    }
    System.out.println();  // To move to the next line.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2011-05-16
    • 2018-10-12
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多