增加2-d java数组的问题

时间:2013-07-24 09:04:33

标签: java arrays matrix multidimensional-array increment

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

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

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 个答案:

答案 0 :(得分:5)

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

int incr = 0;

在循环中,执行此操作

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

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

答案 1 :(得分:0)

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

int i = 0;

然后将循环内的行更改为

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

答案 2 :(得分:0)

你必须在循环之外增加,因为Array是一个对象,任何对象的数据成员都获得默认值,因此它会为数组的每个元素分配0

int inc = 0;

并在循环中

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

答案 3 :(得分:0)

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

}