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

Java while循环实现整数输入计数求和程序问题排查

Java while循环输入统计问题修复方案

问题根因分析

代码的四个异常问题全部由两个逻辑错误触发:

  • 多余调用scan.next():进入while循环时scan.hasNextInt()已经确认当前输入是整数,直接调用scan.next()会把第一个有效输入直接丢弃,未做统计也未参与求和,同时导致后续需要再调用scan.nextInt()读取第二次输入,所以会出现隔一次才出提示、第一个数丢失的问题。如果第二次输入非整数,scan.nextInt()没有前置类型校验,会直接抛出InputMismatchException,就是输入多个数后输非整数直接报错的问题。
  • 求和逻辑错误:sum = input + input是将当前输入的整数乘以2后覆盖sum的值,没有累加历史求和结果,导致最终求和结果完全错误。

修正后完整代码

import java.util.Scanner;
public class InputSequence
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
        int sum = 0;
        int total = 0;
        while (scan.hasNextInt())
        {
            // 直接读取已校验过的整数,不需要额外调用scan.next()
            int input = scan.nextInt();
            sum += input;
            total++;
            // 处理完当前输入后再打印下一次提示
            System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
        }
        System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
        scan.close();
    }
}

修复效果验证

修改后完全匹配需求:

  • 每次输入后都会正常打印下一次输入提示,不会出现跳过提示的问题
  • 所有输入的整数都会被计入总个数统计
  • 求和为所有输入整数的累加结果,计算正确
  • 任何时候输入非整数都会直接终止循环,打印最终结果,不会抛出异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:18:01