Generate 10 random four-digit numbers in Java

Java 8Object Oriented ProgrammingProgramming

To generated random integer, use the Random class with nextInt. At first, create a Random object −

Random rand = new Random();

The Random above is a random number generator. Now, pick the random numbers one by one. We want 10 random four-digit numbers, therefore loop it until i = 1 to 10 −

for (int i = 1; i<= 10; i++) {
   intresRandom = rand.nextInt((9999 - 100) + 1) + 10;
   System.out.println(resRandom);
}

The following is an example to generate 10 random four-digit numbers −

Example

 Live Demo

import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      Random rand = new Random();
      System.out.println("Random numbers...");
      for (int i = 1; i<= 10; i++) {
         int resRandom = rand.nextInt((9999 - 100) + 1) + 10;
         System.out.println(resRandom);
      }
   }
}

output

Random numbers...
6075
4943
2141
5701
4181
9534
3539
6793
3058
4766
raja
Published on 23-Apr-2019 08:58:34
Advertisements