Java中if语句命中首个true返回值后如何终止后续执行
问题说明
代码需要实现的逻辑为:根据用户输入返回对应回复,用户输入无效内容时最多支持3次尝试输入。当前代码存在的问题是:用户连续输入无效值时运行逻辑正常,但输入yes或no这类有效回答后,程序仍会继续请求用户输入,需要实现首次命中有效输入的判断逻辑后,立刻终止后续代码执行的效果。
原问题代码如下:
import java.util.*; public class Equality { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Do you have a job?(yes/no): "); String response = input.next(); if(response.equalsIgnoreCase("yes")) { System.out.println("You are the breadwinner!"); } else if(response.equalsIgnoreCase("no")) { System.out.println("Keep trying, you will find one!"); } else { System.out.println("Invalid Entry! Try again!"); } response = input.next(); if(response.equalsIgnoreCase("yes")) { System.out.println("You are the breadwinner!"); } else if(response.equalsIgnoreCase("no")) { System.out.println("Keep trying, you will find one!"); } else { System.out.println("Invalid Entry! Try again!"); } response = input.next(); if(response.equalsIgnoreCase("yes")) { System.out.println("You are the breadwinner!"); } else if(response.equalsIgnoreCase("no")) { System.out.println("Keep trying, you will find one!"); } else { System.out.println("Too many invalid entries!"); } } }
问题原因
原代码硬编码了3段串行的输入+判断逻辑,无论前一次输入是否为有效值,都会无条件执行后续的input.next()请求新的输入,没有在识别到有效输入后添加终止逻辑,因此会出现有效输入后仍要求用户继续输入的问题。
修复方案
推荐用循环重构重复逻辑,同时在有效输入分支通过return直接终止main方法执行,避免后续代码运行,修复后代码如下:
import java.util.*; public class Equality { public static void main(String[] args) { Scanner input = new Scanner(System.in); int maxAttempts = 3; for (int i = 0; i < maxAttempts; i++) { System.out.println("Do you have a job?(yes/no): "); String response = input.next(); if(response.equalsIgnoreCase("yes")) { System.out.println("You are the breadwinner!"); // 命中有效输入,直接终止方法,不再执行后续逻辑 return; } else if(response.equalsIgnoreCase("no")) { System.out.println("Keep trying, you will find one!"); // 命中有效输入,直接终止方法 return; } else { if (i == maxAttempts - 1) { System.out.println("Too many invalid entries!"); } else { System.out.println("Invalid Entry! Try again!"); } } } } }
逻辑说明
- 用
for循环统一控制最多3次输入尝试,消除了原代码中重复的判断逻辑,后续如果需要调整最大尝试次数,仅需修改maxAttempts变量值即可 - 每次读取用户输入后,如果匹配
yes/no有效输入,输出对应提示后直接执行return,会立刻终止当前main方法的运行,不会再发起新的输入请求 - 输入无效时,会根据当前是否为最后一次尝试,输出对应的错误提示,3次机会用尽后自动结束程序。
如果不想重构原有代码结构,仅做最小改动即可实现需求:在原代码每一个yes、no的有效判断分支末尾添加return;语句,命中有效逻辑后直接退出方法即可。但这种硬编码重复逻辑的写法可维护性差,不推荐使用。
内容的提问来源于stack exchange,提问作者jorge reyes
相关产品推荐
相关产品推荐

