You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化多字符串比较场景下的Java if判断语句?

简化Java字符串判断的几种方案

原代码的多条件equals判断确实可以简化,这里提供几种实用的方案:

1. 使用集合的contains方法(推荐)

把所有有效选项存入一个集合,通过contains方法直接判断,可读性和扩展性都很强,后续新增选项只需修改集合内容:

Scanner scan = new Scanner(System.in);
String reply = scan.nextLine();

// Java 9+ 可以用Set.of创建不可变集合
Set<String> validChoices = Set.of("rock", "paper", "scissors");
// Java 8 版本写法:Set<String> validChoices = new HashSet<>(Arrays.asList("rock", "paper", "scissors"));

if (validChoices.contains(reply)) {
    // 执行你的业务逻辑
}

2. 使用Switch表达式(Java 12+)

利用Java 12引入的switch表达式特性,语法更简洁:

Scanner scan = new Scanner(System.in);
String reply = scan.nextLine();

boolean isValid = switch(reply) {
    case "rock", "paper", "scissors" -> true;
    default -> false;
};

if (isValid) {
    // 执行你的业务逻辑
}

也可以直接把switch表达式嵌入if条件中:

if (switch(reply) {
    case "rock", "paper", "scissors" -> true;
    default -> false;
}) {
    // 执行你的业务逻辑
}

3. 使用正则表达式matches方法

适合简单场景,通过正则匹配判断字符串是否为指定选项之一:

Scanner scan = new Scanner(System.in);
String reply = scan.nextLine();

// | 表示正则中的或逻辑,matches会做全字符串匹配,刚好符合需求
if (reply.matches("rock|paper|scissors")) {
    // 执行你的业务逻辑
}

内容的提问来源于stack exchange,提问作者JWpark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:06:44