尝试从文件中读取整数时NoSuchElementException?

时间:2016-02-17 05:21:12

标签: java file java.util.scanner

我正在尝试从.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

2 个答案:

答案 0 :(得分:1)

这是因为在while循环中,您已到达文件的末尾。

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

尝试在while循环后重新初始化它。

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

答案 1 :(得分:0)

我认为最好使用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);