本文介紹了按列打印 Java 數組的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試在 Java 中格式化兩個數組以打印如下內容:
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("
");
}
但是我得到了這個格式很差的結果:
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
如何將所有列直接排列在頂部標題下方?
How would I go about lining all the columns up directly under the headers at the top?
有沒有更好的方法來做到這一點?
Is there a better way to go about doing this?
推薦答案
你應該看看格式:
System.out.format("%15.2f", booksPrices[i]);
這將提供 15 個插槽,并在需要時用空格填充它.
which would give 15 slots, and pad it with spaces if needed.
但是,我注意到您沒有右對齊您的數字,在這種情況下,您希望在書籍字段中左對齊:
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]);
這是一個工作片段示例:
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]);
}
導致:
Inventory Number Books Prices
0 This $45.99
1 That $89.34
2 The Other Longer One $12.23
3 Fourth One $1000.30
這篇關于按列打印 Java 數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!