Monday, September 9, 2013

ArrayIndexOutOfBoundsException when array size declared with a variable

ArrayIndexOutOfBoundsException when array size declared with a variable

I am getting ArrayIndexOutOfBoundsException when I declare the array size
with a variable, but not when I declare it with a number.
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;
}
Can someone please explain me why Compiler is thinking I'm going out of
bounds when Compiler itself doesn't know the bound, len?
Thanks!

No comments:

Post a Comment