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

Java中Scanner实现的while循环无法退出问题求助

问题分析

你的代码陷入无限循环的核心原因是Scanner.hasNext()方法的特性:当没有更多输入时,它会阻塞等待用户继续输入,而不是返回false,除非遇到输入流结束(比如控制台输入Ctrl+D)。这导致程序永远无法退出循环,更没法校验输入数字的数量是否等于n。

另外代码里存在未定义的变量(比如valid_input、ordinary_order),不过先聚焦循环和输入数量校验的核心问题。

修复方案

以下提供两种适配不同输入场景的修复思路:

思路1:严格按两行输入处理(第一行n,第二行n个数字)

先读取第一行的n,再读取第二行的完整内容,分割后校验数量与格式:

import java.util.Scanner;

public class Sequ {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean error_input = false;
        
        try {
            // 读取第一行的n
            int n = scan.nextInt();
            scan.nextLine(); // 吃掉n后的换行符,避免干扰下一行读取
            
            if (n <= 0) {
                System.out.println("错误:n必须大于0");
                error_input = true;
            } else {
                // 读取第二行的所有数字字符串
                String secondLine = scan.nextLine();
                String[] numStrs = secondLine.trim().split("\\s+");
                
                // 校验数字数量是否匹配n
                if (numStrs.length != n) {
                    System.out.println("错误:输入的数字数量与n不符");
                    error_input = true;
                } else {
                    int[] inputs = new int[n];
                    // 逐个校验并转换数字
                    for (int k = 0; k < n; k++) {
                        try {
                            inputs[k] = Integer.parseInt(numStrs[k]);
                            if (inputs[k] < 0) {
                                System.out.println("错误:存在负数输入");
                                error_input = true;
                                break;
                            }
                            // 处理顺序判断逻辑(修正原代码k>1的错误,应为k>0)
                            if (k > 0) {
                                if (inputs[k] <= inputs[k-1]) {
                                    // ordinary_order = true; 需先定义该变量
                                }
                            }
                        } catch (NumberFormatException e) {
                            System.out.println("错误:存在非整数输入");
                            error_input = true;
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("错误:输入格式不正确");
            error_input = true;
        } finally {
            scan.close();
        }
        
        // 后续可根据error_input状态做后续处理
    }
}

思路2:允许数字分散在多行,但总数量必须为n

循环读取n次,中途检查是否还有输入,若提前无输入则报错;读取完成后若还有多余输入也报错:

import java.util.Scanner;

public class Sequ {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean error_input = false;
        
        try {
            int n = scan.nextInt();
            
            if (n <= 0) {
                System.out.println("错误:n必须大于0");
                error_input = true;
            } else {
                int[] inputs = new int[n];
                int count = 0;
                
                // 循环读取n次,或直到无输入
                while (count < n && scan.hasNextInt()) {
                    int val = scan.nextInt();
                    if (val >= 0) {
                        inputs[count] = val;
                        // 处理顺序判断逻辑
                        if (count > 0) {
                            if (inputs[count] <= inputs[count-1]) {
                                // ordinary_order = true; 需先定义该变量
                            }
                        }
                        count++;
                    } else {
                        System.out.println("错误:存在负数输入");
                        error_input = true;
                        break;
                    }
                }
                
                // 校验输入数量是否足够
                if (!error_input && count < n) {
                    System.out.println("错误:输入的数字数量不足n个");
                    error_input = true;
                }
                // 校验是否存在多余输入
                if (!error_input && scan.hasNextInt()) {
                    System.out.println("错误:输入的数字数量超过n个");
                    error_input = true;
                }
            }
        } catch (Exception e) {
            System.out.println("错误:输入格式不正确");
            error_input = true;
        } finally {
            scan.close();
        }
    }
}
关键修复点
  • 替换无终止条件的while(scan.hasNext()),改用明确的循环终止逻辑(读取n次或读取整行分割),避免程序阻塞等待输入。
  • 新增输入数量校验:通过字符串分割长度统计,或计数读取到的数字个数,与n做对比。
  • 补充异常处理,覆盖非整数输入、负数、n<=0等异常场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:53:17