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

Java数字while循环读取计数问题:代码输出不符预期求助

代码问题分析与修正

问题点

  1. 循环条件错误:使用||(逻辑或)代替了&&(逻辑与)。判断数值是否在[-20, 25]范围内,需要同时满足inputValue >= -20 和 inputValue <=25。用||会导致所有整数都满足条件(比如-49满足inputValue <=25,循环永远无法终止)。
  2. 计数逻辑冗余:原代码先读取第一个值,循环内计数后又额外加1,逻辑绕且容易出错。

修正方案(推荐用do-while简化逻辑)

import java.util.Scanner;

public class CountRead {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int inputValue;
        int countRead = 0;

        do {
            inputValue = scnr.nextInt();
            countRead++;
        } while (inputValue >= -20 && inputValue <= 25);

        System.out.println("Number of integers read: " + countRead);
    }
}

逻辑说明

  • 用do-while循环先执行读取和计数操作,再判断是否继续循环,逻辑更直观。
  • 每读取一个整数就直接计数,直到遇到不在范围内的数时退出循环,此时countRead就是包含终止数在内的总读取个数。
  • 针对示例输入-13 -49 -17 -16 -11,会先读取-13并计数为1,判断符合范围后继续;再读取-49计数为2,判断不符合范围后退出循环,最终输出Number of integers read: 2,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:17:32