簡體   English   中英

嘗試從文件讀取整數時出現NoSuchElementException嗎?

[英]NoSuchElementException when trying to read integers from a file?

我正在嘗試從.txt文件讀取整數,即使while循環包含hasNextInt來確保要讀取的文件中還有另一個整數,我也會在輸入后直接收到此錯誤。

import java.util.Scanner;
import java.io.*;

public class Part2 {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String prompt = ("Please input the name of the file to be opened: ");
    System.out.print(prompt);
    String fileName = input.nextLine();
    input.close();
    Scanner reader = null;

    try{
      reader = new Scanner(new File(fileName)); 
    }

    catch(FileNotFoundException e){
      System.out.println("--- File Not Found! Exit program! ---"); 
    }

    int num = 0;
    while(reader.hasNextInt()){
      reader.nextInt();
      num++;
    }

    int[] list = new int[num];
    for(int i = 0; i<num; i++){
      list[i] = reader.nextInt(); 
    }

    reader.close();

    System.out.println("The list size is: " + num);
    System.out.println("The list is:");
    print(list);//Method to print out
    }//main
}//Part2

這是因為在while循環中,您已到達文件末尾。

 while(reader.hasNextInt()){
          reader.nextInt();
          num++;
        }

嘗試在while循環之后再次將其重新初始化。

 reader = new Scanner(new File(fileName));

我認為最好像這樣使用List

List list = new ArrayList();
int num = 0;
while(reader.hasNextInt()){
  list.add(reader.nextInt());
  num++;
}

/* this part is unnecessary
int[] list = new int[num];
for(int i = 0; i<num; i++){
  list[i] = reader.nextInt(); 
}
*/
//then
System.out.print(list);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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