英文:
2D array NullPointerException
问题
我在尝试将值存储在一个二维数组中时遇到了NullPointerException
:
int length = red[0].length;
int[][] sums = new int[length][];
for (int i = 0; i < length; i++) {
int total = 0;
for (int j = 0; j < length; j++) {
int val = red[i][j];
total = val + total;
}
sums[0][i] = total;
}
如果我将total
存储在一个一维数组中,它可以正常工作。有人能告诉我为什么会出现这个错误吗?
英文:
I am getting a NullPointerException
when trying to store a value in a 2D array:
int length = red[0].length;
int[][] sums = new int[length][];
for (int i = 0; i < length; i++) {
int total = 0;
for (int j = 0; j < length; j++) {
int val = red[i][j];
total = val + total;
}
sums[0][i] = total;
}
It works fine is I store total
in a 1D array. Can anyone tell me why it's giving me this error?
答案1
得分: 0
我认为内部的数组和也应该有一定的容量。例如:
int[][] sums = new int[length][length];
否则,您正在访问sum[0][i]
,但是无法在索引i
处访问内部数组。
英文:
I belive that inner array of sums should also have certain capacity. For example:
int[][] sums = new int[length][length];
Otherwise you are accessing sum[0][i]
but inner array can’t be accessed at index i
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论