jeudi 12 octobre 2017

What is the most effecient way to generate a new random object in java?

I'm trying to create a randomly generated object in my java game. Because there are over 10 objects to choose from, I want to avoid placing 10 different if() statements in my randomizer method.

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

public Obj objRandomizer(){
    Random rand = new Random();
    String [] elements = {"ele1","ele2", "ele3", "ele4", etc...)
    String newObj = elements[rand.nextInt(9)];
    return ((Obj)newObj());
}

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. Any blaringly obvious trick to this I'm missing? I'm relatively new to java so any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire