Java Switch开关如何避免重复代码

发布时间:2025-05-02 15:34:27 作者:小樊
来源:亿速云 阅读:100

在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(); // 在这里调用公共操作
    }
}

现在,我们已经消除了重复代码,使得代码更加简洁和易于维护。

推荐阅读:
  1. ABAP模拟Java Spring依赖注入的方法
  2. Java使用桥接模式实现开关和电灯照明功能详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Switch语句有哪些使用限制

下一篇:Java Switch开关在大型项目中的应用实践

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》