I am creating a game where a user has to roll two dice and do certain things according to what is rolled. I have one method for rolling the dice, which I call twice to stimulate rolling two dice.
import java.util.Random;
public class test {
public static int dice() {
Random generator = new Random(System.currentTimeMillis());
return generator.nextInt(6) +1;
}
public static void main(String[] args) {
int roll1 = dice();
int roll2 = dice();
System.out.println(roll1);
System.out.println(roll2);
}
}
Consistently, the same number is returned for both rolls, even though they are being called separately.
Note: I was seeding the Random generator with the current time to avoid this.
Any help is much appreciated, I am new to Java!
That happens because you are creating a new Random
object every time in the dice()
method. When you call the method quickly multiple times (within the same millisecond), the Random
objects will have the same seed, which is based on the current system time, and will produce the same random number.
Solution: Don't create a new Random
object every time. Create it once, save it as a member variable, and reuse it.
import java.util.Random;
public class test {
private static final Random generator = new Random();
public static int dice() {
return generator.nextInt(6) + 1;
}
public static void main(String[] args) {
int roll1 = dice();
int roll2 = dice();
System.out.println(roll1);
System.out.println(roll2);
}
}