Java do-while循环if条件满足后仍执行后续代码问题排查
Java do-while答题程序答对仍弹出重试询问的问题修复
问题描述
开发do-while循环答题程序时出现逻辑异常:
- 预期行为:用户输入正确答案"C"后,程序输出答对提示后直接终止,不再询问是否重试
- 实际异常:即使用户输入正确答案触发if条件,程序输出"You are correct!"后仍会执行重试询问、读取重试输入的代码,不会直接终止
原问题代码
package dowhileloops; import java.util.Scanner; public class DoWhileLoops { public static void main(String[] args) { Scanner in = new Scanner (System.in); String res, ans; System.out.println("========================================="); System.out.println(" **** Do-While Loops **** "); System.out.println("=========================================\n"); do{ System.out.println("What is the color of the ocean?"); System.out.println("\nA.) Orange\n\nB.) Green\n\nC.) Blue\n\nD.) Yellow\n\n"); System.out.print("Enter your answer: "); res = in.nextLine(); if (res.equalsIgnoreCase("C")) System.out.println("You are correct!"); else System.out.println("You are wrong!"); System.out.println("Would you like to try again? (Yes/No)"); ans = in.nextLine(); }while(ans.equalsIgnoreCase("Yes")); } }
故障原因
Java中if、else关键字后如果不写大括号{},默认只会控制紧跟在后面的第一行可执行语句,后续靠缩进排版的代码不会被归到分支逻辑里:
- 原代码中
if分支仅包含System.out.println("You are correct!");这一行 else分支仅包含System.out.println("You are wrong!");这一行
后面两行询问重试、读取输入的代码,不属于任何if/else分支,是do-while循环体中必然执行的代码,所以无论答案对错都会运行,才会出现答对了仍弹重试提示的问题。
另外原代码还存在潜在编译风险:如果用户第一次就答对,ans变量从未被赋值就会被用到while条件判断中,会触发编译错误。
修复方案
给if/else分支加上大括号,把对应分支要执行的所有代码都包裹到块内,答对时直接终止循环,答错时才触发重试询问逻辑,同时给ans设置初始值避免编译问题。
修复后代码:
package dowhileloops; import java.util.Scanner; public class DoWhileLoops { public static void main(String[] args) { Scanner in = new Scanner (System.in); String res, ans = ""; System.out.println("========================================="); System.out.println(" **** Do-While Loops **** "); System.out.println("=========================================\n"); do{ System.out.println("What is the color of the ocean?"); System.out.println("\nA.) Orange\n\nB.) Green\n\nC.) Blue\n\nD.) Yellow\n\n"); System.out.print("Enter your answer: "); res = in.nextLine(); if (res.equalsIgnoreCase("C")) { System.out.println("You are correct!"); break; // 答对直接跳出循环 } else { System.out.println("You are wrong!"); System.out.println("Would you like to try again? (Yes/No)"); ans = in.nextLine(); } }while(ans.equalsIgnoreCase("Yes")); } }
提示:日常写Java分支、循环逻辑时,哪怕分支内只有一行代码,也建议显式写上大括号,避免出现这类缩进误导、逻辑归属错误的问题。
内容的提问来源于stack exchange,提问作者Clorky
相关产品推荐
相关产品推荐

