Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
Advertisements