Date: 2011nov4
Language: Java
Q. Java: Generate a random integer in a range
A. There are two ways.
Use Math.random() if you just want one:
int number = (int) Math.floor(Math.random() * biggest); // Gives 0 to biggest - 1
Use the Random class if you want many:
Random random = new Random();
int number = random.nextInt(biggest); // Also gives a number in 0 to biggest - 1
Using the first method, here's a way to make something execute 50% of the time:
// We generate either 0 or 1 and compare it with 0
if ((int) Math.floor(Math.random() * 2) == 0) {
// This will be done half the time
}
else {
// This will also be done half the time
}
We can put that in a function:
boolean isCoinTossHeads() {
return (int) Math.floor(Math.random() * 2) == 0;
}
if (isCoinTossHeads()) {
// its heads
}
else {
// its tails
}