增加2-d java数组的问题

Dev*_*ous 1 java arrays increment matrix multidimensional-array

我一直试图解决这一个练习三天,但我不会得到它.我们的想法是创建一个增量矩阵.程序会询问行和列的大小,然后创建矩阵.

我举一个预期结果的例子:

1   2   3   4
5   6   7   8
Run Code Online (Sandbox Code Playgroud)

这是我得到的:

1   1   1   1
1   1   1   1
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

        public static void main (String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader
                        (System.in));

        // User enters row and column size of the 2D array.
        System.out.print ("Input row size: ");
        int ro = Integer.parseInt(in.readLine());

        System.out.print ("Input column size: ");
        int co = Integer.parseInt(in.readLine());
        System.out.println ("   Array is " + ro + "x" + co);

        // Creating a 2D array.
        int[][] a = new int[ro][co];

        // User enters values, which are put into the array. 
        // This is the part where the code fails.
        System.out.print ("The matrix has " + ro*co + " integer values");
        System.out.println (" (one per line): ");
        for (int r = 0; r < a.length; r++)
            for (int c = 0; c < a[0].length; c++) {
                a [r][c] +=1;
            }

        // Printing the matrix
        System.out.println ("Matrix:");
        for (int r = 0; r < a.length; r++) {
            for (int c = 0; c < a[0].length; c++)
                System.out.print (a[r][c] + " ");
            System.out.println();
        }

        }
Run Code Online (Sandbox Code Playgroud)

pet*_*erp 5

你需要一个循环外的变量来增加,例如

int incr = 0;
Run Code Online (Sandbox Code Playgroud)

在循环内,执行此操作

a [r][c] = ++incr;
Run Code Online (Sandbox Code Playgroud)

目前,您正在递增数组中的每个元素0,因此0+1始终最终为1.