問題描述
我正在嘗試在 Java 中格式化兩個(gè)數(shù)組以打印如下內(nèi)容:
I'm trying to format two arrays in Java to print something like this:
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("
");
}
但是我得到了這個(gè)格式很差的結(jié)果:
But I am getting this poorly formatted result instead:
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
如何將所有列直接排列在頂部標(biāo)題下方?
How would I go about lining all the columns up directly under the headers at the top?
有沒有更好的方法來做到這一點(diǎn)?
Is there a better way to go about doing this?
推薦答案
你應(yīng)該看看格式:
System.out.format("%15.2f", booksPrices[i]);
這將提供 15 個(gè)插槽,并在需要時(shí)用空格填充它.
which would give 15 slots, and pad it with spaces if needed.
但是,我注意到您沒有右對(duì)齊您的數(shù)字,在這種情況下,您希望在書籍字段中左對(duì)齊:
However, I noticed that you're not right-justifying your numbers, in which case you want left justification on the books field:
System.out.printf("%-30s", books[i]);
這是一個(gè)工作片段示例:
Here's a working snippet example:
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]);
}
導(dǎo)致:
Inventory Number Books Prices
0 This $45.99
1 That $89.34
2 The Other Longer One $12.23
3 Fourth One $1000.30
這篇關(guān)于按列打印 Java 數(shù)組的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!