Java - Best way to print 2D array?

前端 未结 12 749
庸人自扰
庸人自扰 2020-11-22 15:07

I was wondering what the best way of printing a 2D array was. This is some code that I have and I was just wondering if this is good practice or not. Also correct me in any

12条回答
  •  无人及你
    2020-11-22 15:50

    Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):

    System.out.print(" ");
    for (int row = 0; row < array[0].length; row++) {
        System.out.print("\t" + row );
    }
    System.out.println();
    for (int row = 0; row < array.length; row++) {
        for (int col = 0; col < array[row].length; col++) {
            if (col < 1) {
                System.out.print(row);
                System.out.print("\t" + array[row][col]);
            } else {
    
                System.out.print("\t" + array[row][col]);
            }
        }
        System.out.println();
    }
    

提交回复
热议问题