Date: 2011nov4
Update: 2025oct21
Language: Java
Q. Java: Generate a random integer in a range
A. There are two ways.
Use Math.random() if you just want one:
class Demo {
public static final void main(String []args) {
final int biggest = 100;
int number = (int) Math.floor(Math.random() * biggest); // Gives 0 to biggest - 1
System.out.println("number=" + number);
}
}
Or use the Random class if you want many:
import java.util.Random;
class Demo {
public static final void main(String []args) {
final int biggest = 100;
Random random = new Random();
for (int i = 0; i < 10; i++) {
int number = random.nextInt(biggest); // Gives a number in 0 to biggest - 1
System.out.println("number=" + number);
}
}
}
Output (one time):
number=76
number=93
number=67
number=95
number=8
number=19
number=41
number=99
number=90
number=30
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
}