[英]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++;
}
}
}
填充維度數組的for循環正確運行了兩次,但是在第三次迭代中,我遇到了ArrayIndexOutOfBounds:4異常,我不知道為什么。 2d數組的大小是正確的,我需要該計數器n以便我可以通過二元數組,並且每次通過while循環時它都應自行重置。 (所有內容都包含在try / catch塊中,但是就此而言,無法為格式問題添加“ try”。)
這是堆棧跟蹤。
java.lang.ArrayIndexOutOfBoundsException: 4
at P1.readLineSegments(P1.java:49)
at P1.main(P1.java:16)
您在錯誤的位置使用了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
}
如果您使用的是n ++,則如果它是4x4數組,它將上升16。
它可以是dimensions[k][j]
或dimtoke[n]
。 k
是尺寸的長度,因此毫無疑問。 j
是0..3(如果它如代碼所示那樣簡單。那么dimensions[0].length
可以替換為4。)
唯一的問題是dimtoke[n]
,看來令牌的大小小於4 * dimensions.length
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.