Java编程练习:实现4次有效数字输入校验(限指定流程语句实现)
原代码典型问题定位
- 语法层面:
while判断行末尾多余的分号直接截断循环逻辑,后续代码存在无前置if匹配的孤立else分支,无法通过Java编译 - 逻辑层面:引入了未定义的
pass、pass2变量,没有按需求统计有效数字输入的累计次数,非法输入的重试流程完全错位 - 合规层面:代码中使用了要求未提及的
for循环,没有按照指定的while、if、if-else、do语句实现流程
符合要求的可运行实现代码
import java.util.Scanner; public class InputCheck { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int validInputCount = 0; // 外层while循环:累计满4次有效输入即退出 while (validInputCount < 4) { boolean inputPassed; // do语句块:处理单次输入的校验逻辑,非法输入自动重试 do { System.out.print("Input a number: "); if (scan.hasNextInt()) { scan.nextInt(); validInputCount++; inputPassed = true; } else if (scan.hasNextLine()) { // 丢弃非法输入,避免Scanner死循环 scan.next(); inputPassed = false; } else { inputPassed = false; } } while (!inputPassed); } System.out.println("success."); scan.close(); } }
运行效果校验
- 每次合法数字输入会被累计计数,计数满4次后直接输出
success. - 输入非数字内容时,程序不会计入有效次数,会自动重新发起
Input a number:提示,直到输入合法数字为止 - 代码实现完全使用指定的语句类型:外层
while循环、内层do-while重试逻辑、分支判断使用if和if-else结构,没有使用额外的for循环
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

