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

Java奇偶求和程序未实现输入确认逻辑致无限循环求助

问题分析与修复方案

你的程序存在两个核心问题,导致无法正常询问用户是否继续输入:

1. Scanner输入缓冲区的换行残留问题

sc.nextInt()只会读取输入的数字部分,当用户输入数字后按下回车,回车产生的换行符\n会留在输入缓冲区中。后续调用sc.nextLine()时,会直接读取这个空的换行符,导致变量s为空字符串,程序跳过判断逻辑直接进入下一次循环。

2. 字符串比较错误

Java中用==比较字符串是比较对象的内存引用,而非实际内容。即使用户输入"no"或"yes",s == "no"这种写法也无法正确匹配,应该使用equals()或equalsIgnoreCase()方法来比较字符串内容。


修复后的代码

import java.util.*;
public class EvenOdd_sum{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int sumEven=0;
        int sumOdd=0;
        boolean continueInput=true;
        while(continueInput){
            System.out.println("Enter the number:");
            int n=sc.nextInt();
            // 处理nextInt()留下的换行符
            sc.nextLine();
            
            if(n%2==0){
                sumEven+=n;
            }
            else{
                sumOdd+=n;
            }
            
            System.out.println("Enter yes or no for more inputs:");
            String s = sc.nextLine(); 

            // 使用equalsIgnoreCase忽略大小写,提升用户体验
            if (s.equalsIgnoreCase("no")){
                continueInput=false;
            } else if(!s.equalsIgnoreCase("yes")){
                // 处理无效输入,默认继续
                System.out.println("Invalid input, continuing...");
            }
        }
        System.out.println("Sum of even numbers="+sumEven);
        System.out.println("Sum of odd numbers="+sumOdd);
        sc.close(); // 关闭Scanner释放资源
    }
}

额外优化点

  • 变量名sum1、sum2改为sumEven、sumOdd,提高代码可读性
  • 添加sc.close()关闭Scanner,避免资源泄漏
  • 增加无效输入处理,当用户输入非"yes"/"no"时提示并默认继续

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:57:27