java - 尝试从文件读取整数时出现 NoSuchElementException?

标签 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

最佳答案

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

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

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

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

关于java - 尝试从文件读取整数时出现 NoSuchElementException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35448527/

相关文章:

java - 从磁盘加载存储的 RSA 公钥/私钥?

java - Spring Security - 在 Controller 中获取登录用户 - 礼貌

java - @InjectMocks 和非模拟对象(Spring Data Repositories)

java - useDelimiter 忽略空白以及两个特定符号的正确参数

java - 如何在 Java 中要求用户在循环中重新输入某个字符串时只打印一次文本

java - 使用扫描仪和异常读取文本文件中的整数并存储到数组

java - 检查图形绘制的尺寸

java - 如何验证具有有效扩展名的文件?

ruby-on-rails - Rails 文件上传错误 "undefined method ` original_filename' for nil :NilClass"

Android 外部存储 BufferedWriter 不接受 NewLine