Java:具有两个变量的2D数组
我有一个二维数组。我有值Java:具有两个变量的2D数组,java,arrays,Java,Arrays,我有一个二维数组。我有值x和值y。我希望每个x可以给每个y一个值。因此,如果存在1x和2y: First x, first y: 5 (gives random value) First x, second y: 3 (3 is a random value) 我希望数组存储数组中每个x获得的每个y的每个值。这是我得到的,但是它不能像我希望的那样工作: int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert
x
和值y
。我希望每个x可以给每个y一个值。因此,如果存在1x
和2y
:
First x, first y: 5 (gives random value)
First x, second y: 3 (3 is a random value)
我希望数组存储数组中每个x
获得的每个y
的每个值。这是我得到的,但是它不能像我希望的那样工作:
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;
}
如您所见,我希望
x
和y
能够变化。我尝试过调试它,但是没有成功。看起来您忘记了递增计数器2
。我还建议更改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 (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;
}
}
while(计数器1
当然,for循环更具可读性:
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 (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;
}
}
for(int counter1=0;counter1
Ah。愚蠢的错误。非常感谢。