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.
EDIT: i want to mention that all of these cases are VOID so i dont know how to implement them with a list. And i am at java 7 cant change to java 8 so interface is kinda hard to manage
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);
actions[index].execute();
Make a list of the things to select from
List<Choice> choices = new List<Choice>();
choices.add(something);
choices.add(somethingElse);
...
Choice random = choices.get(new Random().nextInt(choices.size()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.