Home page

Monday, June 5, 2023

Generate Random number between specific range in JAVA

import java.util.Random;

public class RandomNumberInRangeExample {

    public static void main(String[] args) {

        int min = 1; // Minimum value (inclusive)

        int max = 10; // Maximum value (inclusive)

        Random random = new Random();

        int randomNumber = random.nextInt(max - min + 1) + min;

        System.out.println("Random number between " + min + " and " + max + ": " + randomNumber);

    }

}

In this example, we define the minimum and maximum values of the desired range. The nextInt() method is called on the Random object, but this time we provide the range as an argument by subtracting the minimum value from the maximum value and adding 1. This ensures that the generated random number falls within the desired range. The generated random number is then assigned to the randomNumber variable. Finally, the random number is printed to the console using System.out.println().

No comments:

Post a Comment