How to display random numbers less than 20 in Java



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]
Updated on: 2019-07-30T22:30:25+05:30

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements