HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Generating Even Random Numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomevengeneratingnumbers

Problem

I have this class which is used as part of a game. It needs to generate Random Even values, which is done by generating random numbers until the result is even.

Is there a better way to do this?

Also, I currently have the methods implemented as private instance methods, but should I declare generateRandomNumber() and evenNumber(number) as static methods? Will it have any benefits?

public class Game {
    //...

    public void opponentSaysEvenNumber() {
        int number = generateRandomEvenNumber();
        System.out.println("Opponent: " + number);
    }

    private int generateRandomEvenNumber() {
        Random random = new Random();
        int number = random.nextInt();
        while (!evenNumber(number)) {
            number = random.nextInt();
        }
        return number;
    }

    private boolean evenNumber(int number) {
        return (number % 2) == 0;
    }
}

Solution

Yes. I would go one step further and declare your functions as private static final, if possible. The combination of those three keywords means that the code would be unaffected by any instance variable, any superclass, or any subclass, and is also not callable by any code external to the class. Therefore, the compiler has enough of a hint that it could decide to inline the entire function.

I would also rename evenNumber(int number) to isEven(int number). There is a convention in Java that functions named isSomething() return a boolean and have no side effects. Your function meets those criteria.

To generate a random even number, you could just take random.nextInt() & -2 to mask off the least significant digit. That would be more efficient than looping, testing, and discarding. In that case, the whole question about helper functions would be irrelevant.

It's bad practice to create a new instance of Random every time you want to generate one random number, though. The pseudorandom number generator actually carries some state, even if you don't think of it that way. You should therefore use a private static variable to store the Random object.

Context

StackExchange Code Review Q#39359, answer score: 43

Revisions (0)

No revisions yet.