가장 긴 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]);
}
}
}
http://docs.oracle.com/javase/7/docs/api/java /util/Formatter.html은 출력을 정렬하는 방법을 보여줍니다. 예를 들면 다음과 같습니다. formatter.format (Locale.FRANCE, "e = % + 10.4f", Math.E); 여기서 10은 등호와 인쇄되는 숫자 사이의 "공백"수이고 4는 소수 자릿수입니다. –