How to Generate Random Number
A random number is a value that is created without any pattern or order.
Here you will learn that, How to Generate Random Number program in Java using two different ways. To generate Random numbers list, we will use random() method in Java.
Program 1 – Generate Random Number
1 2 3 4 5 6 7 8 9 10 11 | import java.util.Random; public class RandomNumber{ public static void main(String[] args) { // make a Random object Random random = new Random(); // generate random number from 0 to <100 int randomNumber = random.nextInt(100); // print number System.out.println("Random Number: " + randomNumber); } } |
Output
C:\CodeRevise\java>javac RandomNumber.java
C:\CodeRevise\java>java RandomNumber
Random Number: 82
C:\CodeRevise\java>java RandomNumber
Random Number: 50
C:\CodeRevise\java>java RandomNumber
Random Number: 84
C:\CodeRevise\java>java RandomNumber
Random Number: 9
Program 2 – How to Generate n Random numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.Random; import java.util.Scanner; public class RandomNumber{ public static void main(String[] args) { // make a Random object Random rn = new Random(); Scanner scanner = new Scanner(System.in); System.out.print("How many Random number you want to generate : "); int n = scanner.nextInt(); System.out.print("Enter upper limit : "); int upper = scanner.nextInt(); scanner.close(); // generate n random number from 0 to < limit System.out.println(n +" " + "Random Numbers are : "); for(int i=1;i<=n;i++) { int randomNumber = rn.nextInt(upper); // print number System.out.println(" " + randomNumber); } } } |
Output
C:\CodeRevise\java>javac RandomNumber.java
C:\CodeRevise\java>java RandomNumber
How many Random number you want to generate : 7
Enter upper limit : 100
7 Random Numbers are :
42
53
99
4
61
1
97
Check out our other Java Programming Examples