当我用变量声明数组大小时,我得到 ArrayIndexOutOfBoundsException,但当我用数字声明它时却没有。
static Student[] readFile(String filename) {
.........
LineNumberReader lnr = null;
try {
lnr = new LineNumberReader(new FileReader(new File(filename)));
lnr.skip(Long.MAX_VALUE);
len = lnr.getLineNumber();
lnr.close();
} catch (IOException e1) {
e1.printStackTrace();
}
len--; // discount the first line
len = (len > 40) ? 40 : len;
Student[] s = new Student[len]; <------- replacing len with a number resolves it
try {
f = new BufferedReader(new FileReader(new File(filename)));
while ((line = f.readLine()) != null) {
.........
s[roll] = new Student(SID, marks); <--- Exception thrown here
roll++;
if (roll == 41) {
f.close();
throw new CustomException("41st Student!!");
}
}
f.close();
} catch (IOException e) {
e.printStackTrace();
} catch (CustomException e) {
System.out.println("Too many students in the class!");
}
return s;
}
有人可以解释一下为什么当编译器本身不知道界限时,编译器会认为我越界了,len?
谢谢!