如何在控制台输出上对齐String

时间:2012-10-09 05:52:07

标签: java string console formatter

我要编写代码:

Multiplication Tables  Description: Print out the grade school multiplication table upto 12*12

我写了代码:

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 ,但找不到任何解决我问题的好方法。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:36)

您可以根据需要使用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这是整数的格式说明符..
  • {li> 5 %5d表示输出的总宽度。因此,如果您的值为5,则会打印出5个空格,如下所示: - ****5 < / LI>
  • %5d用于对齐 ..对于左对齐,您可以使用%-5d。对于值5,这会将输出打印为: - 5****

答案 1 :(得分: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

由于我无法回答我的问题,因为我提出问题和答案,因为我要回答问题,这是一种不同的数组格式。

答案 2 :(得分:0)

输出的格式化可以使用System.out.format(&#34;&#34;,&#34;&#34;)方法完成此方法包含两个输入参数首先定义格式化样式,然后定义第二个要打印的价值。我们假设你想要n位数右对齐。你将传递第一个参数&#34;%4d&#34;。

左对齐使用-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.
}