The RandomNumbers
class generates random integers between specified ranges.
The class contains a single method named main
, which is the entry point of the program.
The method first generates a random integer between 0 and 9 and displays the result. This is done by using the Math class method Math.random()
to generate a random decimal value between 0 and 1. This decimal value is then multiplied by 10 and the result is cast to an integer using (int)
. Finally, the Math.floor()
method is used to round the result down to the nearest whole number.
Similarly, two more random integers are generated between 1 and 10, and 0 and 100, respectively. The results are displayed using the println
method.
This program demonstrates how to generate random integers in Java using the Math class.
public class RandomNumbers {
public static void main(String[] args) {
System.out.print("Random value between 0 - 9:\t");
int randomInteger10 = (int) Math.floor(Math.random() * 10);
System.out.println(randomInteger10);
System.out.print("Random value between 1 - 10:\t");
int randomInteger = (int) Math.floor(Math.random() * 10) + 1;
System.out.println(randomInteger);
System.out.print("Random value between 0 - 100:\t");
int randomInteger100 = (int) Math.floor(Math.random() * 101);
System.out.println(randomInteger100);
}
}
Random value between 0 - 9: 8
Random value between 1 - 10: 8
Random value between 0 - 100: 16
Random value between 0 - 9: 9
Random value between 1 - 10: 3
Random value between 0 - 100: 95