Java中while循环处理用户输入:二次输入No无法退出问题
问题分析与修复方案
核心问题点
- 循环条件错误:原代码中
while (yes = true)是赋值操作而非判断,每次循环都会强制将yes设为true,导致即使手动设置yes = false,循环也永远无法终止。 - 后续选择逻辑缺失:处理第二次询问时,仅对
no做了退出标记,但未对yes做状态更新,同时没有处理无效输入的情况。 - 字符串判断冗余:多次使用
equals("yes") || equals("Yes"),代码冗余且不够友好。
修复后的完整代码
import java.util.Scanner; public class A3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name; double L1, L2, L3, ES; boolean yes = true; System.out.println("Welcome to the Total XP calculation program!"); System.out.print("Do you want to enter gamer's data? Yes/No => "); String y_n = sc.nextLine(); // 修复循环条件:使用布尔值判断而非赋值 while (yes) { if (y_n.equalsIgnoreCase("yes")) { System.out.print("Enter gamer's name: "); name = sc.next(); System.out.println("Enter gamer's Level XP scores separated by space: L1 L2 L3 ES => "); L1 = sc.nextDouble(); L2 = sc.nextDouble(); L3 = sc.nextDouble(); ES = sc.nextDouble(); // 简化XP计算逻辑,提取公共因子 double score = L1 * 1.2 + L2 * 1.3 + L3 * 1.5 + ES * 1.6; System.out.println("Gamer's name: "+name + " L1 = "+L1 + " L2 = " +L2 + " L3 = " +L3 + " ES = " +ES); System.out.println("Final XP score with bonuses= "+score); System.out.println("\nDo you want to enter another gamer's data? Yes/No => "); sc.nextLine(); // 清空nextDouble残留的换行符 String choice = sc.nextLine(); if (choice.equalsIgnoreCase("no")) { System.out.println("Thank you for using the Total XP calculator!"); yes = false; } else if (choice.equalsIgnoreCase("yes")) { // 更新状态,让下一次循环继续录入 y_n = choice; } else { System.out.println("Invalid input, exiting program."); yes = false; } } else if (y_n.equalsIgnoreCase("no")) { System.out.println("Thank you for using the Total XP calculator!"); yes = false; } else { System.out.println("Invalid input, exiting program."); yes = false; } } sc.close(); // 关闭Scanner资源,避免泄漏 } }
关键修改说明
- 循环条件修复:将
while (yes = true)改为while (yes),确保循环仅在yes为true时执行。 - 字符串判断优化:使用
equalsIgnoreCase()方法,支持大小写不敏感的输入匹配,提升用户体验。 - 完善选择逻辑:新增对
yes输入的状态更新,同时处理无效输入的场景,避免程序异常。 - 代码简化:将XP计算式简化为提取公共因子的形式,逻辑等价且更易读。
- 资源管理:程序结束前关闭
Scanner,规范资源使用。
内容的提问来源于stack exchange,提问作者Humera Butool
相关产品推荐
相关产品推荐

