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

Java程序Scanner提前关闭引发NoSuchElementException问题求助

问题分析与修复方案

问题根源

  • 每次调用getInput()都会新建Scanner实例,且在finally块中关闭它。关闭Scanner时会连带关闭底层的System.in输入流,导致后续循环调用getInput()时,scanner.nextLine()因输入流已关闭抛出NoSuchElementException。
  • 代码中split("\\\\s+")是错误的,Java字符串中匹配任意空白字符的正则应为\\s+(单个反斜杠需转义为两个)。
  • 未校验分割后的输入token数量是否为5,若输入不足5个整数,会导致数组未完全赋值,后续逻辑出错。

修复方案

  1. 复用Scanner实例:在main方法中创建唯一的Scanner实例,传递给getInput()方法使用,避免重复关闭System.in。
  2. 修正分割正则:将split("\\\\s+")改为split("\\s+"),正确分割空白分隔的输入。
  3. 前置输入校验:在解析整数前,先检查分割后的token数量是否为5,不符合则直接返回错误状态。
  4. 调整资源管理:不在getInput()中关闭Scanner,由main方法在程序结束时统一关闭。

修改后的完整代码

import java.util.Scanner;

public class Checker {
    public static class outputVal{
        private String polarity, type;

        public outputVal(String x, String y){
            this.polarity = x;
            this.type = y;
        }
        public String getPolarity() {
            return polarity;
        }
        public String getType() {
            return type;
        }
    }

    // 接收外部传入的Scanner,避免重复创建和关闭
    public static int[] getInput(Scanner scanner){
        try{
            String input = scanner.nextLine();
            String [] inputTokens = input.split("\\s+");
            
            // 先校验输入数量是否为5
            if(inputTokens.length != 5){
                System.out.println("[ERROR] Please enter exactly 5 integers!!!");
                return new int[0];
            }
            
            int [] intTokens = new int[5];
            for(int i=0; i<inputTokens.length; i++){
                intTokens[i] = Integer.parseInt(inputTokens[i]);
            }
            return intTokens;
        }
        catch(NumberFormatException e){
            System.out.println("[ERROR] Enter only integers!!!");
            return new int[0];
        }
    }

    public static String checkPolarity(int x){
        if(x == 0){
            return "Zero";
        } else {
            return x > 0 ? "Positive" : "Negative";
        }   
    }

    public static String evenOdd(int x){
        // 处理负数取模的情况,确保奇偶判断准确
        return Math.abs(x) % 2 == 0 ? "Even" : "Odd";  
    }   

    public static String checkValue(int[] x){
        if(x.length < 2) return "N/A";
        if(x[0] == x[x.length - 1]){
            return "Equal";
        } else {
            return x[0] > x[x.length - 1] ? "Greater" : "Lesser";
        }   
    }
    
    public static void main(String[] args) {
        int[] input = new int[0];
        Scanner scanner = new Scanner(System.in);

        while(input.length == 0){
            System.out.print("Enter five integers: ");
            input = getInput(scanner);
            if(input.length == 0 ){
                System.out.println("[ERROR] Inappropriate Data. Please try again.");
            }
        }

        outputVal[] output = new outputVal[input.length];

        for(int i= 0; i<input.length; i++){
            output[i] = new outputVal(checkPolarity(input[i]), evenOdd(input[i])); 
        }

        for(int i= 0; i<input.length; i++){
            System.out.printf("The number '%d' is %s, %s %n", input[i], output[i].getPolarity(), output[i].getType());
        }

        System.out.printf("%nThe first number is %s than the last number", checkValue(input));
        
        // 程序结束时统一关闭Scanner
        scanner.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 17:10:58