anon432342
anon432342

Reputation: 17

How to randomly choose what code should be run?

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
        }

Upvotes: 1

Views: 51

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

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.

Upvotes: 2

Related Questions