You need to enable JavaScript to run this app. java.util.Scanner抛出NoSuchElementException异常原因及解决方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

java.util.Scanner抛出NoSuchElementException异常原因及解决方法咨询

异常原因

java.util.NoSuchElementException在你调用scan.nextInt()时抛出,核心原因是Scanner读取的System.in标准输入流中已经没有可用的整数元素:你当前的代码连续调用4次nextInt(),要求必须输入至少4个用空白符(空格、换行、制表符等)分隔的整数,只要输入的整数数量不足4个,就会触发该异常。
常见触发场景包括:

  • 手动运行程序时输入的整数数量少于4个,或提前结束了输入流(Windows按Ctrl+Z、Linux/macOS按Ctrl+D都会主动结束输入流)
  • 通过管道、文件重定向方式给程序传入输入内容时,传入内容中的有效整数数量不足4个
  • 其他代码提前关闭了System.in流,导致Scanner读取时流已经处于结束状态
修复方案
  1. 调用nextInt()前先通过hasNextInt()方法判断是否还有可用整数,避免直接读取抛出异常,修复后代码如下:
import java.util.Scanner;

public class FractionTester
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int num1, num2, num3, num4;
        if (scan.hasNextInt()) {
            num1 = scan.nextInt();
        } else {
            System.out.println("缺少第1个整数输入");
            return;
        }
        if (scan.hasNextInt()) {
            num2 = scan.nextInt();
        } else {
            System.out.println("缺少第2个整数输入");
            return;
        }
        if (scan.hasNextInt()) {
            num3 = scan.nextInt();
        } else {
            System.out.println("缺少第3个整数输入");
            return;
        }
        if (scan.hasNextInt()) {
            num4 = scan.nextInt();
        } else {
            System.out.println("缺少第4个整数输入");
            return;
        }
        scan.close();
        // 后续业务逻辑
    }
}

如果嫌逐行判断繁琐,也可以用循环简化校验逻辑。
2. 确保输入符合程序要求:手动运行时依次输入4个整数,用空格或换行分隔,全部输入完成后再执行后续操作;如果是通过文件重定向传入输入,确保文件内包含至少4个有效整数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 04:45:09