这是一个潜在的解决方案,它将根据最长的 bookTypes 值设置 bookType 列的宽度(即 bookTypes 值的格式)。
public class Test {
public static void main(String[] args) {
String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" };
double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 };
// Find length of longest bookTypes value.
int maxLengthItem = 0;
boolean firstValue = true;
for (String bookType : bookTypes) {
maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length());
firstValue = false;
}
// Display rows of data
for (int i = 0; i < bookTypes.length; i++) {
// Use %6.2 instead of %.2 so that decimals line up, assuming max
// book cost of $999.99. Change 6 to a different number if max cost
// is different
String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n";
System.out.printf(format, i + 1, bookTypes[i], costs[i]);
}
}
}