Programming Examples
Java program to Generate a random number between given range
Write a Java Program which accept Lower bound (min) and Upper Bound (max) from user and generate a random number between min and max.Â
Solution
import java.util.Scanner;
public class RandomNumberGenerator
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter the lower bound (min): ");
int min = sc.nextInt();
System.out.print("Enter the upper bound (max): ");
int max = sc.nextInt();
int randomNumber=min + (int)(Math.random() * ((max - min) + 1));
System.out.println("Random number between " + min + " and " + max + ": " + randomNumber);
}
}
Output
Enter the lower bound (min): 1000
Enter the upper bound (max): 9999
Random number between 1000 and 9999: 1182