如何在控制台输出中对齐字符串

17

我需要编写代码来实现:

乘法表说明:打印出小学1-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,但没有找到解决我的问题的好方法。有人能帮我吗?


2
@khachik:你能否描述一下String.format(%4s", ...)是如何工作的?format()中的第二个参数是什么? - Mohammad Faisal
4个回答

40

您可以使用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
  • %5d中的数字5表示输出的总宽度。因此,如果您的值为5,它将被打印成覆盖5个空格,如下所示:****5
  • %5d 用于右对齐。要进行左对齐,可以使用 %-5d。对于值5,这将打印出: - 5****

谢谢。它起作用了。你能在你的回答中描述一下format()%5s是如何工作的吗? - Mohammad Faisal
@MohammadFaisal,你可以使用%5d来打印整数。我会在帖子中解释。 - Rohit Jain
@MohammadFaisal:请查看[javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...)),其中提供了指向详细信息的链接。 - Nandkumar Tekale
@RohitJain:上面的输出需要%4s还是%5s - Mohammad Faisal
@MohammadFaisal.. 您可以提供任何可以容纳您宽度的值..请看我的解释..如果您对 12345 使用 %4s,它将无法适应宽度 4 - Rohit Jain
我该如何将值对齐到屏幕中心或右侧? - Syed Danish Haider

3
在我的例子中,数组包含了不同长度的字符串,因此我无法整理字符串,并且其他数组中的不同字符串在控制台上也不匹配。通过不同的概念,我可以在控制台上整理这些数组。以下是我的代码。
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

由于我因为无法提问和回答而被封禁,所以我无法回答我的问题,我引用了我的答案,这是一种不同类型的数组格式,我感觉。


这并没有提供问题的答案。如果您想对作者进行批评或请求澄清,请在他们的帖子下面留言-您始终可以在自己的帖子上发表评论,一旦您拥有足够的 声誉,您就可以评论任何帖子 - AlBlue
由于我无法回答我提出的问题,因为被阻止提问和回答,所以我引用了我的答案,这是一种不同的数组格式。 - Sunil Bhagwat

0

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

要左对齐,请使用负的 %-nd

要右对齐,请使用正的 %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.
}

0
我创建了一个OutputFormatter类,它可以格式化你提供的字符串:
OutputFormatter formatter = new OutputFormatter();
formatter.add("Asus", "20000");
formatter.add("INTEL", "45000");
formatter.add("Nvidia gtx 1050ti", "17000");
formatter.add("Asus", "18000");
formatter.add("Samsung", "20000");
formatter.add("Coolermaster", "20000");
formatter.add("Ortis", "4000");
formatter.add("Asus", "4000");
System.out.println(formatter.format());

输出结果如下:

Asus              20000
INTEL             45000
Nvidia gtx 1050ti 17000
Asus              18000
Samsung           20000
Coolermaster      20000
Ortis             4000 
Asus              4000 

您可以在OutputFormatter上使用add()方法添加任意数量的字符串,它会将它们全部考虑在内。

这是OutputFormatter类:

import java.util.ArrayList;
import java.util.List;

public class OutputFormatter {
    private List<String[]> contents;

    public OutputFormatter() {
        contents = new ArrayList<>();
    }

    public void add(String... fields) {
        contents.add(fields);
    }

    public void clear() {
        contents.clear();
    }

    public String format() {
        StringBuilder ret = new StringBuilder();
        List<Integer> lengths = new ArrayList<>();
        int maxContentLen = 0;
        for (String[] row : contents) {
            maxContentLen = Math.max(maxContentLen, row.length);
        }

        for (int i = 0; i < maxContentLen; i++) {
            int len = 1;
            for (String[] row : contents) {
                try {
                    len = Math.max(len, row[i].length());
                } catch (IndexOutOfBoundsException ignore) {}
            }
            lengths.add(len);
        }

        for (String[] row : contents) {
            for (int i = 0; i < row.length; i++) {
                ret.append(row[i] + " ".repeat(lengths.get(i) - row[i].length() + 1));
            }
            ret.append(System.lineSeparator());
        }

        return ret.toString();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接