How to print a table in Java?
In Java, you can use string formatting and loops to print a table. Here is a simple example:
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();
}
}
}
The above code first defines a two-dimensional string array named data, which contains the data of the table. Then, it calculates the maximum width of each column through a loop and stores it in the columnWidths array. Next, it uses a loop to print the table header, separating lines, and data rows.
The output is as follows:
Name | Age | Gender
------|-----|-------
John | 25 | Male
Alice | 30 | Female
Bob | 18 | Male
By adjusting the data in the array, different tables can be printed.