Java Do-While循环输入0仍不终止 条件判断失效问题求助
问题原因分析
你编写的while(userResponse != 0)判断条件本身不存在语法和逻辑错误,当前方法内置的do-while循环可以正常退出:
- do-while循环的执行规则是先执行一次循环体代码,再判断条件是否成立,条件为true则继续执行循环体,为false则直接退出循环
- 从你贴出的运行日志可以看出,第一次输入0后,程序已经执行完当前
menu_received()方法的全部逻辑,循环已经正常退出 - 后续再次弹出菜单,是因为你外层调用代码重复执行了
menu_received()方法:第二次调用该方法时,total会重新初始化为0,输入0后输出的结果也正好对应新调用的计算结果,完全符合多次调用该方法的表现。
修正方案
方案1:去除外层重复调用(推荐)
检查你调用menu_received()的上层代码,删除外层的循环逻辑,仅在需要触发点单流程时调用一次该方法即可解决问题。
方案2:优化当前方法逻辑(可选)
你也可以对当前menu_received()方法的细节做优化,避免异常输入和无效逻辑执行:
public static double menu_received() { Scanner input = new Scanner(System.in); int userResponse, total = 0; do { System.out.println(); System.out.println("Here is our menu:"); System.out.println("1. Bulgogi -- $15.00"); System.out.println("2. Kalbi -- $18.00"); System.out.println("3. Kimchi Fried Rice -- $16.00"); System.out.println("Please choose one option at one time using the number (0 to end the order):"); userResponse = input.nextInt(); System.out.println("User Menu choice is " + userResponse); // 输入0直接跳过后续订单处理逻辑 if (userResponse == 0) { break; } else if (userResponse == 1) { System.out.println("Thank you for ordering Bulgogi"); total = total + 15; System.out.println("Your total is $" + total); } else if (userResponse == 2) { System.out.println("Thank you for ordering Kalbi"); total = total + 18; System.out.println("Your total is $" + total); } else if (userResponse == 3) { System.out.println("Thank you for ordering Kimichi Fried Rice"); total = total + 16; System.out.println("Your total is $" + total); } else { // 新增非法输入提示 System.out.println("Invalid option, please choose again."); } } while (userResponse != 0); double total2 = total + 2.55; System.out.println("Your total after tax is $" + total2); return total2; }
内容的提问来源于stack exchange,提问作者user16701881
相关产品推荐
相关产品推荐

