首页 > 解决方案 > 从内部切换 case 语句和运行方法

问题描述

我在开关盒中使用随机数。所以有类似的东西:

public void something {
Random myRand = new Random();
int number = myRand.nextInt(10 - 1) + 1;
switch(number)
case 1:
     Do something and on completion go back and start running the something method again.
break:
case 1;
     Do something and on completion go back and start running the something method again.
break;

每个 case 语句可以根据用户的输入运行任意次数,有些甚至可能不使用。

我想要的是案例声明中的内容:-

public void something (run);

我正在尝试做的事情是可能的还是有更好的方法?

标签: javaandroidswitch-statement

解决方案


我可以建议你使用接口吗?您尝试实现的内容称为函数式编程,其中您将函数作为参数传递给另一个函数

java通过使用接口以某种方式支持函数式编程,并且具有许多内置接口来简化流程

我建议你看看 java.util.function 包

现在让我们开始你的代码

public void something(Supplier<Void> function) {
    boolean condition = true; //use this boolean to control your loop
    while (condition) {
        Random myrand = new Random();
        int number = myrand.nextInt(10 - 1) + 1;
        switch (number) {
            case 1:
                function.get();
                break;
            case 2:
                function.get();
                break;
        }
    }
}

你可以这样称呼你的“东西”

public void Call() {

    //if you want to declare the function only once
    something(new Supplier<Void>() {
        @Override
        public Void get() {
            System.out.println("the job is done!");
            return null;
        }
    });

    // if you already have a class implementing supplier
    something(new MyFunction());
}

并不是因为您的函数没有任何输入而使用了 Supplier 接口,您还可以使用 Consumer、BiConsumer、Function、BiFunction .... 用于具有输入的函数


推荐阅读