Reputation: 69
I am trying to read a series of integers from a file into an ArrayList but when accessing numbers.get(0), I get the Out of Bounds Exception, presumably because nothing has been written to the list.
ArrayList<Integer> numbers = new ArrayList<Integer>();
public void Numbers() throws IOException{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
numbers.add(inputFile.nextInt());
}
inputFile.close();
}
Any help would be greatly appreciated. I can provide more code snippets if needed.
Upvotes: 0
Views: 1908
Reputation: 34397
I think its trying to read the token as int
and comes out with exception. Try this:
try{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String next = inputFile.next();
try{
numbers.add(Integer.valueOf(next));
}catch(NumberFormatException nfe){
//not a number, ignore it
}
}
}catch(IOException ioe){
ioe.printStackTrace();
}
Upvotes: 1
Reputation: 83597
One likely problem is that you have declared the method as
public void Numbers() throws IOException
This is a method called Numbers
which returns void
and throws IOException
. Note that this is not a constructor, which you might intend it to be, because you have declared a return type. If you are calling numbers.get(0)
in another method of this same class. This Numbers()
method is probably not called explicitly if you expect it to be called automatically as a constructor.
Upvotes: 4