[英]Don't understand why I am getting index out of bounds exception when filling this 2d array
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.charAt(0) != '#') {
c++;
// looking to get dimensions from file.
// getting size of array from lines of input.
dimensions = new int[c][4];
// Split my file input into an array of tokens(strings)
tokens = line.split(",");
for (int i = 0; i < tokens.length; i++) {
// Parse strings to int.
dimtoke[i] = Integer.parseInt(tokens[i]);
}
int n = 0;
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
// Error here when trying to put dimtoke into dimensions
(ERROR HERE)dimensions[k][j] = dimtoke[n];
n++;
}
}
}
The for loop to fill the dimensions array runs twice correctly, on the third iteration however, I am getting an ArrayIndexOutOfBounds:4 exception and I can't figure why. 填充维度数组的for循环正确运行了两次,但是在第三次迭代中,我遇到了ArrayIndexOutOfBounds:4异常,我不知道为什么。 The size of the 2d array is correct, I need that counter n so that i can go through dimtoke array and it should reset itself each time through the while loop.
2d数组的大小是正确的,我需要该计数器n以便我可以通过二元数组,并且每次通过while循环时它都应自行重置。 (This is all contained in a try/catch block, but couldn't add the 'try' for formatting issues on this sight.)
(所有内容都包含在try / catch块中,但是就此而言,无法为格式问题添加“ try”。)
Here's the stack trace. 这是堆栈跟踪。
java.lang.ArrayIndexOutOfBoundsException: 4
at P1.readLineSegments(P1.java:49)
at P1.main(P1.java:16)
You have n++ in the wrong spot. 您在错误的位置使用了n ++。
int n = 0;
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
// Error here when trying to put dimtoke into dimensions
(ERROR HERE)dimensions[k][j] = dimtoke[n];
}
n++; //it should be here
}
Where you have n++ it will go up 16 if it is a 4x4 array. 如果您使用的是n ++,则如果它是4x4数组,它将上升16。
it can be dimensions[k][j]
or dimtoke[n]
. 它可以是
dimensions[k][j]
或dimtoke[n]
。 k
is the length of dimension so it is out of question. k
是尺寸的长度,因此毫无疑问。 j
is 0..3 ( if it is as simple as code shows. so dimensions[0].length
can be replaced with 4.) j
是0..3(如果它如代码所示那样简单。那么dimensions[0].length
可以替换为4。)
the only problem is with dimtoke[n]
and it seems size of your tokens are less than 4 * dimensions.length
唯一的问题是
dimtoke[n]
,看来令牌的大小小于4 * dimensions.length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.