To generate a random double
, you can look at this question, however, this problem can more easily be solved by generating random int
s.
In your situation, generating an int
between 0
to 3
is what you want because checking if it is 0
will be true 25% of the time (1 Value / 4 Possible values = 25%).
EDIT: If you would like to also generate a random number to see how many spawn a Guppy will have use threadLocalRandomInstance.nextInt(int bound);
like before.
These constraints can be translated to code like this:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
ThreadLocalRandom tlr = ThreadLocalRandom.current();
int num = tlr.nextInt(3 + 1); //Bound is exclusive so add 1.
int spawn;
if(num == 0) {
spawn = tlr.nextInt(100 + 1); //Again, bound is exclusive so add 1.
} else spawn = 0;
System.out.println("This guppy had " + spawn + " spawn.");
}
}
I use ThreadLocalRandom
as it is more straightforward as supported by this answer.
If you are not using Java 1.7+, use Random#nextInt(int)
instead as also shown by that answer.