Java简易乘法游戏Bug求助:正确答案仍执行else分支
问题排查与解决
嘿,我马上就发现了你代码里的几个关键问题,这应该就是导致正确答案却走else分支的原因啦!
1. 字符串比较的致命错误
你用active == "true"来判断循环是否继续,这在Java里是典型的新手坑!==运算符比较的是字符串对象的内存地址,而不是字符串的实际内容。哪怕active的值是"true",它和字面量"true"的引用地址也可能不一样,导致循环逻辑出问题(不过这可能不是答案判断的直接原因,但必须先修正)。
正确的写法应该用equals()方法:
while ("true".equals(active)) { // 用equals比较字符串内容,而且把字面量放前面避免空指针
2. 答案判断的核心问题(大概率是这里!)
从你截断的代码来看,你应该是生成了两个随机数做乘法,但很大概率是用户输入的处理和类型匹配出了问题:
- 如果你用
Scanner读取输入时用了next()(得到字符串),然后直接和int类型的正确结果比较,类型不匹配肯定会判断为错误 - 或者你读取输入时转int出错,但没处理异常,导致逻辑走偏
举个正确的答案判断示例:
// 先确保你有Scanner实例读取输入 Scanner sc = new Scanner(System.in); // 假设你生成两个随机数相乘 int num1 = r.nextInt(High - Low) + Low; int num2 = r.nextInt(High - Low) + Low; int correctResult = num1 * num2; // 提示用户输入 System.out.print(num1 + " × " + num2 + " = "); // 直接读取int类型的输入,避免字符串转义问题 int userAnswer = sc.nextInt(); // 现在用==比较两个int就没问题了 if (userAnswer == correctResult) { correct++; System.out.println("太棒了,答对了!"); } else { System.out.println("哎呀,答错啦,正确答案是" + correctResult); }
3. 小优化:Random实例不要放循环里
你现在每次循环都new一个Random对象,这会导致随机数的分布不够均匀,而且浪费资源。把Random的创建移到循环外面就好:
Random r = new Random(); // 放在while循环之前 while ("true".equals(active)) { // 这里直接用r生成随机数就行 }
修正后的完整代码片段
import java.util.Random; import java.util.Scanner; public class MultiplicationGame { public static void partB() { System.out.println("Exercise 1B"); int count = 0; String active = "true"; int correct = 0; Random r = new Random(); Scanner sc = new Scanner(System.in); while ("true".equals(active)) { int Low = 10; // inclusive int High = 21; // not inclusive int num1 = r.nextInt(High - Low) + Low; int num2 = r.nextInt(High - Low) + Low; int correctResult = num1 * num2; System.out.printf("%d × %d = ? ", num1, num2); int userAnswer = sc.nextInt(); if (userAnswer == correctResult) { correct++; System.out.println("答对啦!"); } else { System.out.println("答错了,正确答案是 " + correctResult); } // 询问是否继续游戏 System.out.println("继续游戏?输入true继续,false退出:"); active = sc.next(); count++; } System.out.println("游戏结束!总共玩了" + count + "题,答对了" + correct + "题"); sc.close(); } public static void main(String[] args) { partB(); } }
你可以试试这段代码,应该就能解决正确答案走else分支的问题啦!
内容的提问来源于stack exchange,提问作者Babz
相关产品推荐
相关产品推荐

