在Java中,switch语句用于根据一个变量的值执行不同的代码块。如果你需要根据多个条件执行不同的代码块,可以使用以下方法:
int condition1 = 2;
int condition2 = 3;
switch (condition1) {
case 1:
// 处理condition1为1的情况
switch (condition2) {
case 1:
// 处理condition1为1且condition2为1的情况
break;
case 2:
// 处理condition1为1且condition2为2的情况
break;
default:
// 处理其他condition2的情况
break;
}
break;
case 2:
// 处理condition1为2的情况
break;
default:
// 处理其他condition1的情况
break;
}
int condition1 = 2;
int condition2 = 3;
if (condition1 == 1) {
if (condition2 == 1) {
// 处理condition1为1且condition2为1的情况
} else if (condition2 == 2) {
// 处理condition1为1且condition2为2的情况
} else {
// 处理其他condition2的情况
}
} else if (condition1 == 2) {
// 处理condition1为2的情况
} else {
// 处理其他condition1的情况
}
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
int condition1 = 2;
int condition2 = 3;
Map<String, Consumer<Integer>> actions = new HashMap<>();
actions.put("1-1", (c2) -> System.out.println("Condition1: 1, Condition2: " + c2));
actions.put("1-2", (c2) -> System.out.println("Condition1: 1, Condition2: " + c2));
actions.put("2", () -> System.out.println("Condition1: 2"));
String key = condition1 + "-" + condition2;
if (actions.containsKey(key)) {
actions.get(key).accept(condition2);
} else {
System.out.println("No action found for the given conditions.");
}
}
}
这种方法可以让你的代码更加简洁和易于扩展。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。