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

Java代码出现NoSuchElementException异常,问题原因是什么?

java.util.NoSuchElementException 异常原因分析与修复

异常触发原因

你遇到的NoSuchElementException是调用Scanner.nextInt()时抛出的,核心原因是Scanner无法从输入流中读取到下一个有效的整数元素,结合你的代码场景,主要有两种触发情况:

  • 输入流提前终止
    当用户在控制台输入过程中提前关闭输入流(Windows按Ctrl+Z,Linux/macOS按Ctrl+D),或者输入来源(如文件)的内容不足以满足读取需求时,Scanner的hasNextInt()会返回false,此时强行调用nextInt()就会抛出该异常。比如你要求用户输入3个数字,但用户只输入2个就终止了输入,第三次调用nextInt()就会触发异常。

  • 非整数输入导致的缓冲区阻塞
    你的代码仅校验了输入数字是否为正整数,但完全没有处理非整数输入的场景。如果用户输入的是字符串(如abc)、小数(如12.5)这类非整数内容,sc.nextInt()会先抛出InputMismatchException,但无效内容会残留在Scanner的缓冲区中。如果程序未捕获该异常并清除缓冲区,后续再次调用nextInt()时,Scanner仍会读取到这些无效内容,hasNextInt()返回false,进而抛出NoSuchElementException。

代码修复建议

1. 增加输入合法性校验

在每次调用nextInt()前,先用hasNextInt()判断是否有可用的整数输入,同时清除缓冲区中的无效内容,确保输入流程正常:

import java.util.Scanner;
public class MyProgram
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Question 1");
        System.out.print("How many numbers do you have?: ");
        // 先校验是否为有效整数
        while (!sc.hasNextInt()) {
            System.out.println("请输入有效的整数!");
            sc.next(); // 清除缓冲区的无效内容
            System.out.print("How many numbers do you have?: ");
        }
        int count = sc.nextInt();
        // 再校验是否为正整数
        while (!(count > 0)) {
            System.out.println("Enter a non-negative integer.");
            while (!sc.hasNextInt()) {
                System.out.println("请输入有效的整数!");
                sc.next();
                System.out.print("How many numbers do you have?: ");
            }
            count = sc.nextInt();
        }
        
        int num = 0;
        int appearances = 0;
        System.out.print("\nEnter your numbers here...\n");
        for (int i = 1; i <= count; i += 1) {
            System.out.print("第" + i + "个数字:");
            // 读取数字时同样校验合法性
            while (!sc.hasNextInt()) {
                System.out.println("请输入有效的整数!");
                sc.next();
                System.out.print("第" + i + "个数字:");
            }
            num = sc.nextInt();
            if (num == 13) {
                appearances += 1;
            }
        }
        
        // 补充未找到13的输出逻辑
        if (appearances > 0) {
            System.out.print("\n13 was here!");
        } else {
            System.out.print("\nno 13 was found");
        }
        sc.close();
    }
}

2. 补充核心逻辑缺失

你的原始代码未实现“未找到13时输出no 13 was found”的需求,修复后的代码已经补充了这部分逻辑,保证功能完整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:03:12