You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用Scanner时抛出java.util.NoSuchElementException异常如何修复

错误原因

该异常的直接诱因是输入流System.in被提前关闭:

  • 你在enterInfo方法中创建了绑定System.in的Scanner keyboard对象,方法结束前调用了keyboard.close()。Scanner的close操作会直接关闭其绑定的底层输入流,全局唯一的System.in被关闭后,main方法中循环执行到myVal.nextInt()时,尝试从已关闭的输入流读取数据,就会抛出NoSuchElementException。
  • 额外存在的小问题:Scanner.nextInt()只会读取输入的整数内容,不会消费整数后的换行符,后续如果用同一个Scanner调用nextLine()会直接读取到残留的空换行,需要额外处理。
修复步骤
  1. 全局仅创建一个绑定System.in的Scanner实例,不要在子方法中重复创建Scanner。可以将main方法中的myVal定义为静态全局变量,或者将其作为参数传入enterInfo方法。
  2. 移除enterInfo方法中所有keyboard.close()调用,程序运行全程不要关闭绑定System.in的Scanner,进程退出时系统会自动回收相关资源。
  3. 调用nextInt()后手动调用一次nextLine()消费残留的换行符,避免后续读取行内容出现异常。
修复后参考代码
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class file {
    // 全局共用同一个Scanner
    static Scanner myVal = new Scanner(System.in);
    static ArrayList<newType> studInfo = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        int choice = 0;
        while(choice != 3) {
            System.out.println("1. enter info \n2. print info \n3.exit");
            System.out.println("Enter a choice: ");
            choice = myVal.nextInt();
            // 消费nextInt残留的换行符
            myVal.nextLine();

            if(choice == 1) {
                enterInfo();
            } else if(choice == 2) {
                print();
            } else if(choice == 3) {
                System.exit(0);
            }
        }
        // 程序完全退出前再关闭Scanner,此处可省略
        myVal.close();
    }

    static void enterInfo() {
        System.out.println("Enter the information (Program year average lastname): ");
        String info = myVal.nextLine().trim();
        if(info.isEmpty()) {
            System.out.println("Error, no input was made.");
            return;
        }
        String[] tokens = info.split(" ");
        String prgm = tokens[0];
        int yr = Integer.parseInt(tokens[1]);
        Double avg = Double.parseDouble(tokens[2]);
        String lastname = tokens[3];
        newType inf = new newType(prgm, yr, avg, lastname);
        studInfo.add(inf);
        System.out.println("Information added.");
    }
    
    // 原有print方法自行保留即可
    static void print() {
        // 原有打印逻辑
    }
}

// 此处补充你原有newType类的定义即可
class newType {
    String prgm;
    int yr;
    Double avg;
    String lastname;

    public newType(String prgm, int yr, Double avg, String lastname) {
        this.prgm = prgm;
        this.yr = yr;
        this.avg = avg;
        this.lastname = lastname;
    }
}

内容的提问来源于stack exchange,提问作者Angel93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:18:00