Java:具有两个变量的2D数组

时间:2015-10-24 09:03:03

标签: java arrays

我有一个2D数组。我的值为x,值为y。我希望每个x都可以为每个y赋值。因此,如果有1x2y

First x, first y: 5 (gives random value)

First x, second y: 3 (3 is a random value)

我希望数组存储数组中每yx得到的每个值。这就是我得到的,但是它不能按照我的要求运行:

    int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value to x"));
    int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value to y"));
    int[][] array = new int[x][y];
    int counter1 = 0;
    int counter2 = 0;

    while (x > counter1) {
        while (y > counter2) {
            int value = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value x gives to the current y"));
            array[counter1][counter2] = value;
        }
        counter1++;
        counter2 = 0;
    }

如您所见,我希望xy能够改变。我试过调试它,但没有任何成功。

1 个答案:

答案 0 :(得分:2)

您似乎忘了增加counter2。我还建议在while条件下更改操作数的顺序,以使代码更具可读性:

while (counter1 < x) {
    while (counter2 < y) {
        int value = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value x gives to the current y"));
        array[counter1][counter2] = value;
        counter2++; // added
    }
    counter1++;
    counter2 = 0;
}

当然for循环会更具可读性:

for (int counter1 = 0; counter1 < x; counter1++) {
    for (int counter2 = 0; counter2 < y; counter2++) {
        int value = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value x gives to the current y"));
        array[counter1][counter2] = value;
    }
}