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は小数点以下の桁数である。 –