在列中打印Java数组

我正在尝试用Java格式化两个数组来打印这样的东西:

Inventory Number Books Prices ------------------------------------------------------------------ 1 Intro to Java $45.99 2 Intro to C++ $89.34 3 Design Patterns $100.00 4 Perl $25.00 

我使用以下代码:

 for(int i = 0; i < 4; i++) { System.out.print(i+1); System.out.print(" " + books[i] + " "); System.out.print(" " + "$" + booksPrices[i] + " "); System.out.print("\n"); } 

但我得到了这个格式不佳的结果:

 Inventory Number Books Prices ------------------------------------------------------------------ 1 Intro to Java $45.99 2 Intro to C++ $89.34 3 Design Patterns $100.0 4 Perl $25.0 

我如何直接在顶部的标题下面排列所有列?

有没有更好的方法来做这件事?

你应该看看格式:

 System.out.format("%15.2f", booksPrices[i]); 

这将提供15个插槽,并在需要时用空格填充它。

但是,我注意到你没有正确certificate你的数字,在这种情况下你想在书籍领域左对齐:

 System.out.printf("%-30s", books[i]); 

这是一个工作片段示例:

 String books[] = {"This", "That", "The Other Longer One", "Fourth One"}; double booksPrices[] = {45.99, 89.34, 12.23, 1000.3}; System.out.printf("%-20s%-30s%s%n", "Inventory Number", "Books", "Prices"); for (int i=0;i 

导致:

 Inventory Number Books Prices 0 This $45.99 1 That $89.34 2 The Other Longer One $12.23 3 Fourth One $1000.30 

您可以使用

 System.out.printf(...) 

用于格式化输出。 那用

 String.format(...) 

使用

 java.util.Formatter 

你可以在这里找到文档。

要对齐简单的String,您可以使用以下内容:

 String formatted = String.format("%20s", str) 

这将是前置

 20 - str.length 

实际String之前的空白并将返回填充的字符串。 例如,如果您的String是“Hello,World!” 它会增加11个空白:

 " Hello, World!" 

要将某些内容对齐到左侧,您必须在指示结果字符串长度的数字前面添加“ – ”。

要安全地对齐所有内容,首先必须找出最长的字符串。

不使用任何库,您需要确定每个coloumn的最大长度并适当地附加所需的空格字符。 例如这样:

 /** * Determines maximum length of all given strings. */ public static int maxLength(int padding, String... array) { if (array == null) return padding; int len = 0; for (String s : array) { if (s == null) { continue; } len = Math.max(len, s.length()); } return len + padding; } /** * Unifies array element lengths and appends 3 whitespaces for padding. */ public static String[] format(String[] array) { if (array == null || array.length == 0) return array; int len = maxLength(3, array); String[] newArray = new String[array.length]; for (int i = 0; i < array.length; i++) { newArray[i] = array[i]; while (newArray[i].length() < len) { newArray[i] += " "; } } return newArray; }