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. 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. (This is all contained in a try/catch block, but couldn't add the 'try' for formatting issues on this sight.)
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.
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.
it can be dimensions[k][j]
or dimtoke[n]
. k
is the length of dimension so it is out of question. j
is 0..3 ( if it is as simple as code shows. so dimensions[0].length
can be replaced with 4.)
the only problem is with dimtoke[n]
and it seems size of your tokens are less than 4 * dimensions.length
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.