This question already has an answer here:
how to system.out.println on the same line(java) [duplicate]
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
我正在尝试一些二维数组示例。当我尝试以以下格式打印二维数组输出时

0 1 2

3 4 5

6 7 8

9 10 11

12 13 14


我的输出像这样显示

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14


不确定是什么问题

这是我的代码:

public class TwoDArray {

    public static void main(String[] args) {
        int rows = 5;
        int columns = 3;
        int k = 0;
        int[][] array = new int[rows][columns];
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++) {
                array[i][j] = k;
                k++;
            }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.println(array[i][j] + " ");
            }
            System.out.println();
        }
    }
}

最佳答案

您已使用:

System.out.println(number)


这将在每个打印数字的末尾创建一个新行。要查看所需的输出,应使用:

System.out.print(number)


码:

public class TwoDArray {
    public static void main(String[] args) {
        int rows = 5;
        int columns = 3;
        int k = 0;
        int[][] array = new int[rows][columns];
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++) {
                array[i][j] = k;
                k++;
            }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }
}

10-05 21:41