簡體   English   中英

嘗試從文件讀取到ArrayList時,索引超出范圍異常

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM