How to display random numbers less than 20 in Java

Java 8Object Oriented ProgrammingProgramming

At first, create a Random class object −

Random rand = new Random();

Now, create a new array −

int num;
int arr[] = new int[10];

Loop through and set the Random nextInt with 20 as parameter since you want random numbers less than 20 −

for (int j = 0; j <= 9; j++) {
   num = 1 + rand.nextInt(20);
   arr[j] = num;
}

Example

 Live Demo

import java.util.Arrays;
import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      Random rand = new Random();
      int num;
      int arr[] = new int[10];
      for (int j = 0; j<= 9; j++) {
         num = 1 + rand.nextInt(20);
         arr[j] = num;
      }
      System.out.println("Random numbers less than 20 = "+Arrays.toString(arr));
   }
}

Output

Random numbers less than 6 = [4, 13, 14, 19, 1, 11, 17, 1, 11, 4]
raja
Published on 24-Apr-2019 12:17:18
Advertisements