如何实现Java猜数字程序在输入错误或输入1时重新执行?
改进后的Java猜数字程序
我来帮你调整这个猜数字程序,让它支持输入非0-10范围的数字时重新输入,以及用户选择输入1时重新玩一局的功能。下面是修改后的完整代码,我会在后面拆解关键的修改点:
package w3school; import java.util.Random; import java.util.Scanner; public class nyttprogram { static void indata() { // 提前初始化Scanner和Random,避免每次循环重复创建对象 Scanner scanner = new Scanner(System.in); Random random = new Random(); boolean shouldContinue; do { shouldContinue = false; int userGuess; // 1. 处理用户输入范围校验:确保输入0-10之间的数字 System.out.println("Input a number from 0-10"); while (!scanner.hasNextInt()) { System.out.println("Please enter a valid integer!"); scanner.next(); // 清空无效输入 } userGuess = scanner.nextInt(); if (userGuess < 0 || userGuess > 10) { System.out.println("Invalid number! It must be between 0 and 10."); shouldContinue = true; // 标记需要重新输入 continue; } // 2. 生成随机数并判断猜测结果 int randomInt = random.nextInt(11); // 修正:nextInt(11)生成0-10的随机数,匹配题目要求 if (userGuess == randomInt) { System.out.println("You guessed the correct number!"); } else { System.out.println("You guessed the wrong number"); System.out.println("The correct number was: " + randomInt); } // 3. 处理重试选择 System.out.println("Input 1 if you want to try again: "); while (!scanner.hasNextInt()) { System.out.println("Please enter a valid integer!"); scanner.next(); // 清空无效输入 } int retryChoice = scanner.nextInt(); if (retryChoice == 1) { shouldContinue = true; // 标记需要重新玩一局 } } while (shouldContinue); // 只要标记为true,就循环执行 scanner.close(); // 关闭Scanner,避免资源泄漏 } public static void main(String[] args) { indata(); } }
关键修改点说明
- 循环结构:用
do-while循环包裹整个游戏逻辑,确保程序至少运行一次,然后通过shouldContinue变量控制是否继续循环 - 输入合法性校验:
- 先判断用户输入是否是整数,避免非数字输入导致程序崩溃
- 校验输入的数字是否在0-10范围内,不符合则提示错误并重新输入
- 重试逻辑:游戏结束后获取用户的重试选择,只有当输入为1时,设置
shouldContinue为true,触发下一轮游戏 - 细节优化:
- 将
Scanner和Random实例移到循环外,避免每次循环重复创建对象 - 修正了随机数生成范围:原代码
nextInt(10)生成0-9的数字,改成nextInt(11)来匹配题目要求的0-10范围 - 最后关闭
Scanner,避免资源泄漏
- 将
内容的提问来源于stack exchange,提问作者TheTutorialGuy
相关产品推荐
相关产品推荐

