English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To generate random numbers in Java, use.
import java.util.Random;
Now, use the Random class to create an object.
Random num = new Random();
Now, use this in a loop.nextInt()
method, as it is used to get the next random integer value. You can also set a range, such as 0 to20, written as.
nextInt( 20);
Let's see a complete example where the range is1to10.
import java.util.Random; public class Demo { public static void main(String args[]) { Random num = new Random(); int res; for (int i = 1; i <= 5; i++ ) { res = 1 + num.nextInt( 10 ); System.out.printf("%d", res); } } }
Output Result
4 5 9 6 9