简体   繁体   中英

Index Out Of Bounds Exception when trying to read from file into ArrayList

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.

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.

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();
 }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM