簡體   English   中英

在Java中以cmd打印表格

[英]Print a table in cmd in java

我有以下矩陣

 1 2 3 4 5 6
 2 3 4 5 6 1
 3 4 5 6 1 2
 4 5 6 1 2 3
 5 6 1 2 3 4
 6 1 2 3 4 5

...我想把它放在桌子上

 | 1 2 3 4 5 6
---------------
1| 1 2 3 4 5 6
2| 2 3 4 5 6 1
3| 3 4 5 6 1 2
4| 4 5 6 1 2 3
5| 5 6 1 2 3 4
6| 6 1 2 3 4 5

具有n個元素是否可以動態打印這樣的表?

    public static void main ( String [ ] args ) {
        int n = Integer.parseInt(args[0]);
        for(int w = 1; w <= n; w++){
            System.out.println("");
            for(int p = w; p <= n + w - 1; p++){
                System.out.print((p-1)%n+1 + " ");
            }           
        }
    }

粗暴,但應該可以。

 //This method adds required number spaces for alignment.
 private static String formatString(String s, int in) {
        return String.format("%1$-" + (in + 1) + "s", s);
    }

    public static void main(String[] args) {    

        int n = Integer.parseInt(args[0]);          
        int in = args[0].length();
        System.out.print(formatString(" ", in));
        System.out.print("| ");

        for (int w = 1; w <= n; w++) {              
            System.out.print(formatString(w + "", in));
        }
        System.out.println("");
        for (int w = 1; w <= n + 2; w++) {
            System.out.print(formatString("-", in));
        }

        for (int w = 1; w <= n; w++) {
            System.out.println("");
            System.out.print(formatString((w + ""), in));
            System.out.print("| ");
            for (int p = w; p <= n + w - 1; p++) {

                System.out.print(formatString(((p - 1) % n + 1) + "", in));
            }
        }

    }

編輯:編輯代碼以考慮對齊問題。

這幾乎可以帶走所有您可以扔給它的東西:

public static void main(String[] args) {
    int[][] matrix = {
        { 1, 2, 3, 4, 5, 6 },
        { 2, 3, 4, 5, 6, 1 },
        { 3, 4, 5, 6, 1, 2 },
        { 4, 5, 6, 11, 2, 3 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 223523526, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 5, 116, 1, 2, 3, 4 },
        { 6, 1, 2, 3, 4, 5 }
    };

    //compute the maximum header width (the number of columns)
    int rows = matrix.length;
    int cols = rows > 0 ? matrix[0].length : 0;
    int maxRowHeaderWidth = Integer.toString(rows).length();

    int maxCellWidth = 1;
    //compute the maximum cell width
    for ( int[] row : matrix ) {
        for ( int cell : row ) {
            maxCellWidth = Math.max(Integer.toString(cell).length(), maxCellWidth);
        }
    }
    maxCellWidth = Math.max(maxCellWidth, Integer.toString(cols).length());

    StringBuilder patternBuilder = new StringBuilder();

    //the header
    for ( int i = 0; i < maxRowHeaderWidth; i++ ) {
        patternBuilder.append(' ');
    }
    patternBuilder.append('|');
    for ( int i = 0; i < cols; i++ ) {
        patternBuilder.append(String.format("%" + (maxCellWidth+1) + "d", i+1));
    }
    patternBuilder.append('\n');


    //the line of dashes
    int rowWidth = patternBuilder.length();
    for ( int i = 0; i < rowWidth; i++ ) {
        patternBuilder.append('-');
    }
    patternBuilder.append('\n');

    //each row
    for ( int i = 0; i < matrix.length; i++ ) {
        patternBuilder.append(String.format("%" + (maxRowHeaderWidth) + "d|", i+1));
        for ( Integer cell : matrix[i] ) {
            patternBuilder.append(String.format("%" + (maxCellWidth+1) + "d", cell));
        }
        patternBuilder.append('\n');
    }

    System.out.println(patternBuilder);
}

無論單元格中數字的長度如何,它均等地調整每個單元格的大小。 它可以占用任意數量的行或列。

取決於陣列,假設您事先知道陣列的大小。 請注意,在Java數組中,子數組的大小不必相同,請注意以下幾點:

對於測試用例:

public static void main(String[] args) {
    System.out.println(toTableString(new int[][] { { 1, 2, 3, 4, 5, 6 },
            { 2, 3, 4, 5, 6, 1 }, { 3, 4, 5, 6, 1, 2 },
            { 4, 5, 6, 1, 2, 3 }, { 5, 6, 1, 2, 3, 4 },
            { 6, 1, 2, 3, 4, 5 } }));
    System.out.println();
    System.out.println(toTableString(new int[][] { { 1 }, { 2, 3 },
            { 3, 4, 5 }, { 4, 5, 6, 1 }, { 5, 6, 1, 2, 3 },
            { 6, 1, 2, 3, 4, 5 } }));
    System.out.println();
    System.out.println(toTableString(new int[][] { { 1 }, { 20, 300 },
            { 3000, 40000, 50000 }}));
}

輸出:

 | 0 1 2 3 4 5 
——————————————
0| 1 2 3 4 5 6 
1| 2 3 4 5 6 1 
2| 3 4 5 6 1 2 
3| 4 5 6 1 2 3 
4| 5 6 1 2 3 4 
5| 6 1 2 3 4 5 

 | 0 1 2 3 4 5 
——————————————
0| 1 
1| 2 3 
2| 3 4 5 
3| 4 5 6 1 
4| 5 6 1 2 3 
5| 6 1 2 3 4 5 

     | 00000 00001 00002 
————————————————————————
00000| 00001 
00001| 00020 00300 
00002| 03000 40000 50000 

在線運行: 鏈接

如果您是我,我將看一下OpenCSV之類的 盡管不是特別適合您的需求,但它們將很有用。

實際上,表格顯示可以看作是打印CSV文件的一種方式。 因此,構建適合此CSV文件的結構並將其打印到System.out可以使用干凈的布局來完成這項工作(盡管就依賴性而言絕對不是最佳選擇)。

   Output:

    +------------+--------------+------------+
    | one        | two          | three      |
    +------------+--------------+------------+
    | super      | broccoli     | flexible   |
    | assumption | announcement | reflection |
    | logic      | pleasant     | wild       |
    +------------+--------------+------------+




    import java.util.ArrayList;
        import java.util.Arrays;
        import java.util.Collections;
        import java.util.List;

        public class CommandLineTable {
            private static final String HORIZONTAL_SEP = "-";
            private String verticalSep;
            private String joinSep;
            private String[] headers;
            private List<String[]> rows = new ArrayList<>();
            private boolean rightAlign;

            public CommandLineTable() {
                setShowVerticalLines(false);
            }

            public void setRightAlign(boolean rightAlign) {
                this.rightAlign = rightAlign;
            }

            public void setShowVerticalLines(boolean showVerticalLines) {
                verticalSep = showVerticalLines ? "|" : "";
                joinSep = showVerticalLines ? "+" : " ";
            }

            public void setHeaders(String... headers) {
                this.headers = headers;
            }

            public void addRow(String... cells) {
                rows.add(cells);
            }

            public void print() {
                int[] maxWidths = headers != null ?
                        Arrays.stream(headers).mapToInt(String::length).toArray() : null;

                for (String[] cells : rows) {
                    if (maxWidths == null) {
                        maxWidths = new int[cells.length];
                    }
                    if (cells.length != maxWidths.length) {
                        throw new IllegalArgumentException("Number of row-cells and headers should be consistent");
                    }
                    for (int i = 0; i < cells.length; i++) {
                        maxWidths[i] = Math.max(maxWidths[i], cells[i].length());
                    }
                }

                if (headers != null) {
                    printLine(maxWidths);
                    printRow(headers, maxWidths);
                    printLine(maxWidths);
                }
                for (String[] cells : rows) {
                    printRow(cells, maxWidths);
                }
                if (headers != null) {
                    printLine(maxWidths);
                }
            }

            private void printLine(int[] columnWidths) {
                for (int i = 0; i < columnWidths.length; i++) {
                    String line = String.join("", Collections.nCopies(columnWidths[i] +
                            verticalSep.length() + 1, HORIZONTAL_SEP));
                    System.out.print(joinSep + line + (i == columnWidths.length - 1 ? joinSep : ""));
                }
                System.out.println();
            }

            private void printRow(String[] cells, int[] maxWidths) {
                for (int i = 0; i < cells.length; i++) {
                    String s = cells[i];
                    String verStrTemp = i == cells.length - 1 ? verticalSep : "";
                    if (rightAlign) {
                        System.out.printf("%s %" + maxWidths[i] + "s %s", verticalSep, s, verStrTemp);
                    } else {
                        System.out.printf("%s %-" + maxWidths[i] + "s %s", verticalSep, s, verStrTemp);
                    }
                }
                System.out.println();
            }

            public static void main(String[] args) {
                //test code
                CommandLineTable st = new CommandLineTable();
                //st.setRightAlign(true);//if true then cell text is right aligned
                st.setShowVerticalLines(true);//if false (default) then no vertical lines are shown
                st.setHeaders("one", "two", "three");//optional - if not used then there will be no header and horizontal lines
                st.addRow("super", "broccoli", "flexible");
                st.addRow("assumption", "announcement", "reflection");
                st.addRow("logic", "pleasant", "wild");
                st.print();
            }


 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM