提问人:okay4 提问时间:2/24/2021 最后编辑:okay4 更新时间:2/24/2021 访问量:149
2D 数组工作、越界错误、for 循环、
2D Array work, out of bounds error, for loop,
问:
我的一个学校作品告诉我们制作一个二维数组,并显示数组中的内容。我不知道为什么它说出界,我有点卡住了。我们的任务是制作 10 个学生证和 3 个测试,每个测试都有分数,如下图所示。for 循环部分设计为在 x 达到 3(显示最终测试分数时)后移动到下一列。
public class TwoDArray {
public static void main(String [] args) {
int [] [] musicScores = { {1001, 2002, 3003, 4004, 5005,6006,7007,8008,9009,1010,},{10,7,8,9,5,10,8,7,6,9},{9,8,10,9,9,10,9,9,7,9},{8,7,8,9,8,7,8,10,8,8}};
int y = 0;
for (int x = 0; x < 4; x++) {
System.out.print(musicScores[x][y] + "\t");
for (x = 3;y < 10; y++) {
x = 0;
System.out.println("");
}
}
}
}
答:
1赞
Dren
2/24/2021
#1
您正在 for 循环中混合逻辑,这是一种在 2D 数组中迭代的方法
public class TwoDArray {
public static void main(String[] args) {
int[][] musicScores = {{1001, 2002, 3003, 4004, 5005, 6006, 7007, 8008, 9009, 1010,}, {10, 7, 8, 9, 5, 10, 8, 7, 6, 9}, {9, 8, 10, 9, 9, 10, 9, 9, 7, 9}, {8, 7, 8, 9, 8, 7, 8, 10, 8, 8}};
for (int i = 0; i < musicScores.length; i++) {
for (int j = 0; j < musicScores[i].length; j++) {
System.out.println("Values at arr[" + i + "][" + j + "] is " + musicScores[i][j]);
}
}
}
}
2赞
CryptoFool
2/24/2021
#2
您的问题是对于该行:
System.out.print(musicScores[x][y] + "\t");
您允许采用 的值 ,该值是无效的数组索引。这样做的原因是您在退出循环后使用:y
10
y
for
for (y = 0;y < 10; y++) {
...
}
当此循环退出时,为 。然后你循环并使用该循环之外,你可能不应该这样做。我不确定你到底想做什么,但也许你想将有问题的线移动到你的内部for循环中,如下所示:y
10
y
class TwoDArray {
public static void main(String [] args) {
int [] [] musicScores = { {1001, 2002, 3003, 4004, 5005,6006,7007,8008,9009,1010,},{10,7,8,9,5,10,8,7,6,9},{9,8,10,9,9,10,9,9,7,9},{8,7,8,9,8,7,8,10,8,8}};
for (int x = 0; x < 4; x++) {
for (int y = 0;y < 10; y++) {
System.out.print(musicScores[x][y] + "\t");
}
System.out.println();
}
}
}
注意:我的答案和 @Dren 提供的答案都相当清理您的代码。设置对你没有好处,如果你只在内部循环中使用,你可能应该这样做,那么最好在循环本身中定义,以确保你不会在循环之外使用它。在原始代码中,内部循环所做的只是打印一堆空行。我怀疑这是你的本意。我们的两种解决方案都不会打印空行。x = 0
y
for
y
for
for
@Dren的回答确实值得注意......它将数组长度的硬编码常量替换为数据集中数组的实际长度。这总是可取的。如果这样做,那么在更改数据集时,不必确保更改硬编码长度值以匹配...很容易出错的东西。
评论
0赞
Dren
2/24/2021
喜欢解释:)
评论
y
for loop