This Java program generates random numbers within the provided range.
This Java program asks the user to provide maximum range, and generates a number within the range.
- Scanner class and its function nextInt() is used to obtain the input, and println() function is used to print on the screen.
- Random class and its function is used to generates a random number.
- Scanner class and Random class is a part of java.util package, so we required to import this package in our Java program.
- We also required to create objects of Scanner class and Random class to call its functions.
Example:
import java.util.Scanner;
import java.util.Random;
class AtRandomNumber
{
public static void main(String[] args)
{
int maxRange;
//create objects
Scanner SC = new Scanner(System.in);
Random rand = new Random();
System.out.print("Please enter maximum range: ");
maxRange=SC.nextInt();
for(int loop=1; loop<=10; loop++)
{
System.out.println(rand.nextInt(maxRange));
}
}
}
Program Output:
Please enter maximum range: 500 467 61 100 449 68 316 445 224 54 498
Sometimes situation arises where random numbers are required to be generated between the ranges.
Generate a Random Number Between the Range
Example:
import java.util.Random;
class HelloWorld
{
public static void main(String[] args)
{
Random rand = new Random();
int minRange = 1000, maxRange= 5000;
int value = rand.nextInt(maxRange - minRange) + minRange;
System.out.println(value);
}
}
Program Output:
3256