C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Random Number Generator within range - Java Program

import java.util.Scanner;

import java.util.Random;

 

public class RandomInRange {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        Random rand = new Random();

 

        System.out.println("===== RANDOM NUMBER GENERATOR =====");

 

        System.out.print("Enter minimum value: ");

        int min = sc.nextInt();

 

        System.out.print("Enter maximum value: ");

        int max = sc.nextInt();

 

        if (min > max) {

            System.out.println("Invalid range! Minimum cannot be greater than maximum.");

            return;

        }

 

        // Generate random number in range [min, max]

        int randomNum = rand.nextInt((max - min) + 1) + min;

 

        System.out.println("\nRandom Number between " + min + " and " + max + " is: " + randomNum);

    }

}

Output

 
OUTPUT :
===== RANDOM NUMBER GENERATOR =====
Enter minimum value: 10
Enter maximum value: 50

Random Number between 10 and 50 is: 34

Explanation of the Program

Import Random and Scanner

import java.util.Random;

import java.util.Scanner;

  • Scanner → read min & max from user
  • Random → generate random numbers

Take Range Input

int min = sc.nextInt();

int max = sc.nextInt();

The user enters:

  • Minimum value
  • Maximum value

Validate Range

if (min > max) {

    System.out.println("Invalid range!");

    return;

}

Prevents invalid input like min = 50, max = 10.

Random Number Formula

int randomNum = rand.nextInt((max - min) + 1) + min;

Explanation:

  • rand.nextInt(n) → generates a number from 0 to n-1
  • So for a custom range [min, max], use:

rand.nextInt(max−min+1)+min\text{rand.nextInt}(max - min + 1) + minrand.nextInt(max−min+1)+min

Example:
min = 10, max = 50 → nextInt(41) gives 0–40 → add 10 → final range 10–50

Display Result

System.out.println("Random Number between " + min + " and " + max + " is: " + randomNum);