Sunstrike
Sunstrike

Reputation: 466

Generate random number java

Have class for generation random numbers:

public class RandomNumber {

    public static int getRandomNumber(int n) {
        return new Random().nextInt(n);
    }
}

Use it in my switch

public crt createNewCrt() {
        if (RandomNumber.getRandomNumber(4) == 1) {
            switch (RandomNumber.getRandomNumber(4)) {
            case 0:
                /../
            case 1:
                /../

            default:
                break;
            }
        }
        return null;
    }

But generation numbers always the same. What the problem?

Upvotes: 0

Views: 804

Answers (4)

Grim
Grim

Reputation: 1986

Set a Seed for the Random like this

Random r = new Random(System.currentTimeMillis());

Because random is always based on calculations, so Random never a real Random.

Upvotes: 0

Cruncher
Cruncher

Reputation: 7812

public class RandomNumber {
    private static Random r = new Random();
    public static int getRandomNumber(int n) {
        return r.nextInt(n);
    }
}

Change your random generation to this. If you instantiate the Random class twice very quickly, it will use the same seed and generate the same numbers. If you hold the object in a static field, then you keep getting the next numbers from the same seed, instead of the first one over and over.

Upvotes: 3

MadConan
MadConan

Reputation: 3767

I'm not exactly sure why you are using a separate method. Why not do:

public crt createNewCrt() {
    Random random = new Random();
    int randomNumber = random.nextInt(4);

    switch (randomNumber) {
        case 0:
            /../
        case 1:
            /../

        default:
            break;
    }

    return null;
}

Upvotes: 0

meyerjp3
meyerjp3

Reputation: 197

You have an if statement at the beginning of your switch. The switch is only called if the random number == 1. You can get rid of the if statement.

Upvotes: 0

Related Questions