Java程式將字串格式化為表格
在本文中,我們將學習如何使用Java將字串格式化為表格。Java的System.out.format() 方法是一種方便顯示格式化輸出的方式。我們將定義一個字串格式,指定列寬以確保統一的間距,從而建立整潔的表格佈局。透過這種方法,我們可以以結構化且易讀的格式顯示多行字串資料,而無需手動調整每個條目的空格。
將字串格式化為表格的步驟
以下是將字串格式化為表格的步驟:
- 使用System.out.format()定義一個格式字串,以指定表格的結構。
- 對每一列使用%-15s格式說明符,它為字串保留15個空格並將其左對齊。
- 建立一個帶有兩個列佔位符的格式字串strFormat。
- 使用System.out.format()對每一對值應用格式字串。
- 每一行將在兩個15個字元寬的列中顯示兩個字串。
- 輸出將顯示為格式化的表格,每個條目都有統一的間距。
Java程式將字串格式化為表格
以下是將字串格式化為表格的Java程式。以下是一個示例:
public class Demo {
public static void main(String []args) {
String strFormat = "|%1$-15s|%2$-15s|
";
System.out.format(strFormat, "One", "Two");
System.out.format(strFormat, "Three", "Four");
System.out.format(strFormat, "Five", "Six");
System.out.format(strFormat, "Seven", "Eight");
System.out.format(strFormat, "Nine", "Ten");
System.out.format(strFormat, "Eleven", "Twelve");
System.out.format(strFormat, "Thirteen", "Fourteen");
System.out.format(strFormat, "Fifteen", "Sixteen");
}
}
輸出
|One |Two | |Three |Four | |Five |Six | |Seven |Eight | |Nine |Ten | |Eleven |Twelve | |Thirteen |Fourteen | |Fifteen |Sixteen |
程式碼解釋
在這個Java程式中,字串strFormat被定義為指定兩列,每列15個字元寬。格式字串使用|%1$-15s|%2$-15s|將文字在每列的15個空格內左對齊。System.out.format() 方法用於將不同的字串對插入格式化表格中。每次呼叫System.out.format()都會在表格中生成一行,其中第一個引數對應第一列,第二個引數對應第二列。輸出以整潔、均勻間隔的兩列表格顯示所有字串對。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP