java如何打印表格

小億
79
2024-01-17 04:34:59

在Java中,可以使用字符串格式化和循環(huán)來(lái)打印表格。下面是一個(gè)簡(jiǎn)單的示例:

public class TablePrinter {
    public static void main(String[] args) {
        String[][] data = {
            {"Name", "Age", "Gender"},
            {"John", "25", "Male"},
            {"Alice", "30", "Female"},
            {"Bob", "18", "Male"}
        };

        // 計(jì)算每列的最大寬度
        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();

        // 打印數(shù)據(jù)行
        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();
        }
    }
}

上述代碼首先定義了一個(gè)二維字符串?dāng)?shù)組data,其中包含表格的數(shù)據(jù)。然后,通過(guò)循環(huán)計(jì)算每列的最大寬度,并存儲(chǔ)在columnWidths數(shù)組中。接下來(lái),使用循環(huán)打印表頭、分隔線和數(shù)據(jù)行。

輸出結(jié)果如下:

Name  | Age | Gender
------|-----|-------
John  | 25  | Male  
Alice | 30  | Female
Bob   | 18  | Male  

通過(guò)調(diào)整數(shù)組data中的數(shù)據(jù),可以打印不同的表格。

0