[英]Index Out Of Bounds Exception when trying to read from file into ArrayList
我试图将文件中的一系列整数读取到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();
}
任何帮助将不胜感激。 如果需要,我可以提供更多代码段。
一个可能的问题是您已将方法声明为
public void Numbers() throws IOException
这是一个称为Numbers
的方法,该方法返回void
并抛出IOException
。 请注意,这不是构造函数,因为您已声明了返回类型,所以您可能不希望这样做。 如果要在同一类的另一个方法中调用numbers.get(0)
。 如果您希望作为构造函数自动调用此Numbers()
方法,则可能不会显式调用它。
我认为它试图将标记读取为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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.