Write Java program to Generate Random Numbers from 0 to given Range


This Java program generates five random numbers within a range specified by the user. The program uses the Scanner and Random classes from the Java utility package to get input from the user and generate random numbers.

The program starts by creating a Scanner object to read input from the user and a Random object to generate random numbers. It then prompts the user to enter the maximum range for the random numbers to be generated.

The program uses a for loop to generate five random numbers within the range specified by the user. The nextInt(max_range) method of the Random object is used to generate random numbers between 0 (inclusive) and max_range (exclusive). The loop iterates five times and prints each random number on a new line using System.out.println().

Overall, this program is a simple way to generate random numbers within a specified range in Java using the Random class. However, it is worth noting that the Random class generates pseudorandom numbers, which means that the sequence of numbers generated is deterministic and can be predicted if the seed value of the Random object is known. For applications requiring more secure random numbers, such as cryptography, it may be necessary to use a different approach.

Source Code

import java.util.Scanner;
import java.util.Random;
class Random_Number
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		Random rand = new Random();
 
		System.out.print("Enter Maximum Range : ");
		int max_range = input.nextInt();
 
		//generate 5 random numbers from 0 to given Range
		for (int i = 1; i <= 5; i++)
		{
			System.out.println(rand.nextInt(max_range));
		}
	}
}

Output

Enter Maximum Range : 100
72
62
89
92
90

Example Programs