您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,使用switch语句时,为了避免重复代码,可以将相同的代码块提取出来,然后根据需要执行不同的操作。这里有一个例子来说明如何实现这个目标:
public class SwitchExample {
public static void main(String[] args) {
int input = 2;
switch (input) {
case 1:
performOperation1();
break;
case 2:
performOperation1(); // 与case 1相同
performOperation2();
break;
case 3:
performOperation3();
break;
default:
System.out.println("Invalid input");
}
}
private static void performOperation1() {
System.out.println("Performing operation 1");
}
private static void performOperation2() {
System.out.println("Performing operation 2");
}
private static void performOperation3() {
System.out.println("Performing operation 3");
}
}
在这个例子中,performOperation1()
方法在case 1和case 2中都被调用了。为了避免重复代码,我们可以将performOperation1()
的调用放在一个单独的地方,然后在需要的地方调用它。这样,我们就可以避免在每个case中重复相同的代码。
修改后的代码如下:
public class SwitchExample {
public static void main(String[] args) {
int input = 2;
switch (input) {
case 1:
performOperation1();
break;
case 2:
commonOperation(); // 调用公共操作
performOperation2();
break;
case 3:
performOperation3();
break;
default:
System.out.println("Invalid input");
}
}
private static void performOperation1() {
System.out.println("Performing operation 1");
}
private static void performOperation2() {
System.out.println("Performing operation 2");
}
private static void performOperation3() {
System.out.println("Performing operation 3");
}
private static void commonOperation() {
performOperation1(); // 在这里调用公共操作
}
}
现在,我们已经消除了重复代码,使得代码更加简洁和易于维护。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。