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

我要写代码:

乘法表说明:打印等级学校乘法表最多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(数字是右对齐的,并在每一行上去掉前导/尾随空格)。 我试过谷歌但没有找到任何解决我的问题的好方法。 有人可以帮帮我吗?

您可以根据需要使用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****

在我的例子中,数组包含不同长度的字符串,由于我无法排列字符串,其他不同数组的字符串在控制台上不匹配。 使用不同的概念,我可以在控制台上安排这些数组我的代码如下。

 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 

既然我无法回答我的问题,我问我的问题,因为我要问问题和答案,我引用了我的答案,这是一种不同的数组格式。

输出的格式化可以使用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. }