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

Java do while循环中输入超0-5范围数字时如何添加用户提示

问题根因
  1. 循环判断逻辑错误:原有代码的内层循环终止条件while (user_selection <= 5 || user_selection>5 || user_selection<0)存在逻辑漏洞,不管输入什么值该表达式结果永远为true,哪怕输入0-5范围内的合法数字也不会退出循环,完全不符合需求。
  2. 缺少范围校验分支:现有代码仅对非整数输入做了错误提示处理,拿到整数输入后没有判断是否在0-5的合法区间内,自然无法输出超范围的错误提示。
修正后的代码片段
int user_selection=0;
do {
    System.out.print("Enter a given number: ");
    // 非整数输入校验
    while (!user_input.hasNextInt()) {
        System.out.println("That's not a number");
        System.out.print("Please Enter only the Number Given: ");
        user_input.next();
    }
    user_selection = user_input.nextInt();
    // 新增范围校验与提示
    if (user_selection < 0 || user_selection >5) {
        System.out.println("Input out of range, please enter a number between 0 and 5");
    }
// 仅当输入超出范围时才继续循环
} while (user_selection < 0 || user_selection >5);
修改说明
  • 修复了循环判断逻辑:合法输入范围是0到5,仅当输入小于0或者大于5时才需要继续循环等待用户输入,合法输入可直接退出循环
  • 新增了范围错误提示:拿到整数后先校验范围,超出范围时直接打印对应提示,引导用户输入正确区间的数字
  • 解决了原代码合法输入也无法退出内层循环的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:06:03