[英]Java: 2D Array with two variables
我有一个二维数组。 我有值x
和值y
。 我希望每个 x 都可以给每个 y 一个值。 所以如果有1x
和2y
:
First x, first y: 5 (gives random value)
First x, second y: 3 (3 is a random value)
我希望数组存储每个y
由数组中的每个x
获得的每个值。 这就是我得到的,但是它不能像我想要的那样工作:
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
能够变化。 我试过调试它,但没有任何成功。
看起来您忘记增加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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.