vendredi 20 octobre 2017

What is the most efficient way to generate a random object in Java? [duplicate]

I'm trying to create a randomizer method which will randomly select a new Monster object to be added to my java game. The problem is there are so many different Monster objects, I want to avoid creating multiple unique if() statements in the method.

I currently have an abstract Monster super class with 10 monster subclasses.

My first thought was to create an array of Strings and then convert them to objects, which didn't work:

public Monster monsterRandomizer(){
    Random rand = new Random();
    String [] monsters = {"bird","zombie","shark",etc...)
    String newMonster = monsters[rand.nextInt(9)];
    return new ((Monster)newMonster());
}

I imagine making this idea work would require a separate method. So I currently just have 10 separate if() statements which I hate the look of:

public Monster monsterRandomizer(){
    Random rand = new Random();
    int i = rand.nextInt(9);

    if (i==0){
        return new Shark();
    }
    if (i==1){
        return new Zomibie();
    }
    if (i==2){
        return new Bird();
    }

    // and so on....

I'm relatively new to java so any help is appreciated. I want to avoid putting 10 different if() statements in my code if at all possible.




Aucun commentaire:

Enregistrer un commentaire