在Java中,可以使用字符串格式化和循环来打印表格。下面是一个简单的示例:
public class TablePrinter { public static void main(String[] args) { String[][] data = https://www.yisu.com/ask/{"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
通过调整数组data
中的数据,可以打印不同的表格。