打印表格

2021-09-13  本文已影响0人  蓝笔头
public class GridPrinter {

    public static void main(String[] args) {
        print(5, 5);
    }

    public static void print(int rows, int columns) {
        for (int i = 1; i < rows; ++ i) {
            printLine('+', '-', columns);
            printLine('|', ' ', columns);
        }
        printLine('+', '-', columns);
    }

    private static void printLine(char delimiter, char padding, int columns) {
        for (int j = 0; j < columns; ++ j) {
            printCell(delimiter, padding);
        }
        System.out.println(delimiter);
    }

    public static void printCell(char delimiter, char padding) {
        // 可以调整表格单元的宽度
        int paddingWidth = 4;
        System.out.print(delimiter);
        for (int j = 0; j < paddingWidth; ++ j) {
            System.out.print(padding);
        }
    }
}

控制台输出:

+----+----+----+----+----+
|    |    |    |    |    |
+----+----+----+----+----+
|    |    |    |    |    |
+----+----+----+----+----+
|    |    |    |    |    |
+----+----+----+----+----+
|    |    |    |    |    |
+----+----+----+----+----+
上一篇 下一篇

猜你喜欢

热点阅读