如何随机选择要运行的代码?

huangapple go评论55阅读模式
英文:

How to randomly choose what code should be run?

问题

除了我这里的写法,是否有一种随机选择要运行的代码的方法?肯定有一种更简单的方法。我知道有关switchcase,但不知道是否可以在case中随机执行一个情况。

Random r = new Random();
int i = r.nextInt(4);

switch (i) {
    case 0:
        // 做某事
        break;
    case 1:
        // 做其他事情
        break;
    case 2:
        // 做其他事情
        break;
    case 3:
        // 做其他事情
        break;
    default:
        // 在没有匹配的情况下执行的代码
        break;
}
英文:

Is there a way to randomly pick what code should run other than how I have it here? There's gotta be an easier way. I know about switch and case but didn't know if I could randomly have a case there.

 Random r = new Random();
        int i = r.nextInt(4);

        if (i == 0) {
            //dosomething
        } else if (i == 1) {
           // dosomethingelse
        } else if(i == 2) {
            //dosomethingelse
        } else if(i == 3) {
            //dosomethingelse
        } else if(i == 4) {
            //dosomethingelse
        }

</details>


# 答案1
**得分**: 2

你当前的代码已经非常优化,至少对于在Java中执行类似操作而言是这样。作为一个指针,你可以重写逻辑以使用`switch`语句,这样至少可以使代码变得更易读:

```java
Random r = new Random();
int i = r.nextInt(5);

switch(i) {
    case 0:
        // 做一些事情
        break;
    case 1:
        // 做另一些事情
        break;
    case 2:
        // 做另一些事情
        break;
    case 3:
        // 做另一些事情
        break;
    case 4:
        // 做另一些事情
        break;
}

注意:如果你想生成一个在0和4之间的随机整数(包括4),则使用nextInt(5)。使用nextInt(4)将永远不会生成值4。

英文:

Your current code is already pretty optimal, at least for how you would do something like this in Java. As a pointer, you could rewrite your logic to use a switch statement, which would at least make the code a bit easier to read:

Random r = new Random();
int i = r.nextInt(5);

switch(i) {
    case 0:
        // do something
        break;
    case 1:
        // do something else
        break;
    case 2:
        // do something else
        break;
    case 3:
        // do something else
        break;
    case 4:
        // do something else
        break;
}

Note: If you want to generate a random integer between 0 and 4 (inclusive of the 4), then use nextInt(5). Using nextInt(4) will never actually generate the value 4.

huangapple
  • 本文由 发表于 2020年10月11日 10:57:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64300218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定