在 Java 中,switch 语句不支持多值匹配。但是,你可以使用以下几种方法来实现类似的功能:
if-else 语句:int value = 2; if (value == 1 || value == 3) { System.out.println("Value is 1 or 3"); } else if (value == 2 || value == 4) { System.out.println("Value is 2 or 4"); } else { System.out.println("Value is not 1, 2, 3, or 4"); } Map 结构:import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class MultiValueSwitch { public static void main(String[] args) { int value = 2; Map<Integer, Consumer<Integer>> actions = new HashMap<>(); actions.put(1, v -> System.out.println("Value is 1")); actions.put(2, v -> System.out.println("Value is 2")); actions.put(3, v -> System.out.println("Value is 3")); actions.put(4, v -> System.out.println("Value is 4")); if (actions.containsKey(value)) { actions.get(value).accept(value); } else { System.out.println("Value is not 1, 2, 3, or 4"); } } } switch 表达式(仅适用于 Java 12 及更高版本):int value = 2; String result = switch (value) { case 1, 3 -> "Value is 1 or 3"; case 2, 4 -> "Value is 2 or 4"; default -> "Value is not 1, 2, 3, or 4"; }; System.out.println(result); 请注意,这些方法并不是真正的 switch 多值匹配,而是使用其他结构来实现类似的功能。