Generate 10 random four-digit numbers in Java


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

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements