thvardhan thvardhan - 11 months ago 49
Java Question

better way to make java do random stuff?

Here is the thing. recently I've been working on a project which is kind of a AI like thing. what i want to do is, i will be given a random number between 0-300 and i have to do a random thing based on that number.

now i can use

switch(/*number b/w 0-300*/){
case 0:
case 1:
so on to 300

i have tried IF-Else cases and apparently they are even more inefficient then switch cases.

but i think there must be a better way to do this because it will take like forever to make soo many cases.

Answer Source

You can define an interface for all the "random things":

interface AIAction {
    public void execute();

and then collect all those actions' implementation in an array. I chose to implement each AIAction using a lambda, but that's ultimately up to you:

static AIAction[] actions = new AIAction[] {
    () -> {System.out.println("a");},
    () -> {System.out.println("b");},
    () -> {System.out.println("c");}

after that, you can just execute a random action like this:

Random rand = new Random();
int index = rand.nextInt(actions.length);