索引超出范围尝试从文件读入ArrayList时出现异常

时间:2012-11-29 00:34:15

标签: java arraylist

我正在尝试从文件中读取一系列整数到ArrayList,但是当访问numbers.get(0)时,我得到了Out of Bounds Exception,大概是因为没有任何内容写入列表。

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

非常感谢任何帮助。如果需要,我可以提供更多代码片段。

2 个答案:

答案 0 :(得分:4)

一个可能的问题是您已将方法声明为

public void Numbers() throws IOException

这是一个名为Numbers的方法,它返回void并抛出IOException。请注意,这是一个构造函数,您可能会想要它,因为您已声明了一个返回类型。如果您在同一个班级的另一个方法中调用numbers.get(0)。如果您希望将其作为构造函数自动调用,则可能不会显式调用此Numbers()方法。

答案 1 :(得分:1)

我认为它试图将令牌读作int并且出现异常。试试这个:

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();
 }
相关问题