简体   繁体   English

尝试从文件读取到ArrayList时,索引超出范围异常

[英]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中,但是当访问numbers.get(0)时,出现了超出界限的异常,大概是因为没有任何内容写入列表中。

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 . 这是一个称为Numbers的方法,该方法返回void并抛出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. 如果要在同一类的另一个方法中调用numbers.get(0) This Numbers() method is probably not called explicitly if you expect it to be called automatically as a constructor. 如果您希望作为构造函数自动调用此Numbers()方法,则可能不会显式调用它。

I think its trying to read the token as int and comes out with exception. 我认为它试图将标记读取为int并出现异常。 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();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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