我正在尝试用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
Run Code Online (Sandbox Code Playgroud)
我使用以下代码:
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");
}
Run Code Online (Sandbox Code Playgroud)
但我得到这个格式不佳的结果:
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
Run Code Online (Sandbox Code Playgroud)
我如何直接在顶部的标题下面排列所有列?
有没有更好的方法来做这个?
你应该看看格式:
System.out.format("%15.2f", booksPrices[i]);
Run Code Online (Sandbox Code Playgroud)
这将提供15个插槽,并在需要时用空格填充它.
但是,我注意到你没有正确对齐你的数字,在这种情况下你想在书籍领域左对齐:
System.out.printf("%-30s", books[i]);
Run Code Online (Sandbox Code Playgroud)
这是一个工作片段示例:
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<books.length;i++){
System.out.format("%-20d%-30s$%.2f%n", i, books[i], booksPrices[i]);
}
Run Code Online (Sandbox Code Playgroud)
导致:
Inventory Number Books Prices
0 This $45.99
1 That $89.34
2 The Other Longer One $12.23
3 Fourth One $1000.30
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1705 次 |
| 最近记录: |