printing out a 2-D array in Matrix format

后端 未结 9 1397
暖寄归人
暖寄归人 2020-12-08 03:13

How can I print out a simple int [][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn\'t apparently work. If it helps

9条回答
  •  囚心锁ツ
    2020-12-08 03:45

        int[][] matrix = {
            {1,2,3},
            {4,5,6},
            {7,8,9}
        };
        //use foreach loop as below to avoid IndexOutOfBoundException
        //need to check matrix != null if implements as a method
        //for each row in the matrix
        for (int[] row : matrix) {
            //for each number in the row
            for (int j : row) {
                System.out.print(j + " ");
            }
            System.out.println("");
        }
    

提交回复
热议问题