1

我已经尝试了三天来解决这个练习,但我不会得到它。这个想法是创建一个递增的矩阵。程序询问行和列的大小,然后创建矩阵。

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

1   2   3   4
5   6   7   8

这是我得到的:

1   1   1   1
1   1   1   1

这是我的代码:

        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();
        }

        }
4

4 回答 4

5

您需要循环外的变量来增加,例如

int incr = 0;

在循环中,执行此操作

a [r][c] = ++incr;

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

于 2013-07-24T09:08:19.980 回答
0

您的循环只是将数组加一。由于所有数组元素都从零开始,因此所有元素都增加 1,因此您的结果。尝试在循环外包含一个变量,例如:

int i = 0;

然后将循环内的行更改为类似

i++;
a[r][c] = i;
于 2013-07-24T09:11:55.200 回答
0

您必须在循环外递增,因为Array任何对象的对象和数据成员都会获得默认值,因此它将分配0给数组的每个元素。

int inc = 0;

并在循环内

a[r][c]=inc++;
于 2013-07-24T09:15:08.993 回答
0

公共静态 void main(String[] args) 抛出 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 incremental purpose
    int counter = 0;
    for (int r = 0; r < a.length; r++)
        for (int c = 0; c < a[0].length; c++) {
            a[r][c] = ++counter;
        }

    // 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();
    }

}
于 2013-07-24T09:15:31.630 回答