This site requires JavaScript, please enable it in your browser!
Greenfoot back
Kartoffelbrot
Kartoffelbrot wrote ...

2013/11/17

Choosing enum randomly

Kartoffelbrot Kartoffelbrot

2013/11/17

#
Hello dear programmers, I want to choose enum's randomly, like this:
static enum test{e1, e2, e3};

        public test randomEnumPicker(){
            int random = Greenfoot.getRandomNumber(3);
            if(random == 0)
                return e1;
            else if(random == 1)
                return e2; 
            else if(random == 2)
                return e3;
        }
I know so far, that I can't cast integers to specific enum types, but is there an easier way? Can I get the possible values of that enum type?
SPower SPower

2013/11/17

#
You could do this:
public test randomEnumPicker()
{
    return test.values()[Greenfoot.getRandomNumber(3)];
}
And just some advice to improve your programming: enums in Java start with an Uppercase letter, so Test would be better than test.
danpost danpost

2013/11/17

#
There is a 'values' method for enums that returns an array containing all the values of the class in the order given. You should be able to use 'test.values()' to get a random enum value.
Kartoffelbrot Kartoffelbrot

2013/11/17

#
Thank you both, that was exactly what I needed! @SPower: ok
You need to login to post a reply.