Reputation: 466
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
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
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
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
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