Javaで表を印刷する方法は何ですか?
Javaでは、文字列のフォーマットとループを使用して表を印刷することができます。以下は簡単な例です:
public class TablePrinter {
public static void main(String[] args) {
String[][] data = {
{"Name", "Age", "Gender"},
{"John", "25", "Male"},
{"Alice", "30", "Female"},
{"Bob", "18", "Male"}
};
// 计算每列的最大宽度
int[] columnWidths = new int[data[0].length];
for (String[] row : data) {
for (int i = 0; i < row.length; i++) {
if (row[i].length() > columnWidths[i]) {
columnWidths[i] = row[i].length();
}
}
}
// 打印表头
for (int i = 0; i < data[0].length; i++) {
System.out.format("%-" + columnWidths[i] + "s", data[0][i]);
System.out.print(" | ");
}
System.out.println();
// 打印分隔线
for (int i = 0; i < columnWidths.length; i++) {
for (int j = 0; j < columnWidths[i] + 3; j++) {
System.out.print("-");
}
}
System.out.println();
// 打印数据行
for (int i = 1; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.format("%-" + columnWidths[j] + "s", data[i][j]);
System.out.print(" | ");
}
System.out.println();
}
}
}
最初のコードでは、データを含む二次元文字列配列dataが定義されます。そして、ループを使用して各列の最大幅を計算し、columnWidths配列に保存します。その後、ループを使用して見出し、区切り線、データ行を印刷します。
結果は以下の通りです:
Name | Age | Gender
------|-----|-------
John | 25 | Male
Alice | 30 | Female
Bob | 18 | Male
データ配列内のデータを調整することで、異なるテーブルを印刷できます。