1package com.mkyong.example.test;
2
3import java.util.Random;
4
5public class TestRandom {
6
7 public static void main(String[] args) {
8
9 for (int i = 0; i < 10; i++) {
10 System.out.println(getRandomNumberInRange(5, 10));
11 }
12
13 }
14
15 private static int getRandomNumberInRange(int min, int max) {
16
17 if (min >= max) {
18 throw new IllegalArgumentException("max must be greater than min");
19 }
20
21 Random r = new Random();
22 return r.nextInt((max - min) + 1) + min;
23 }
24
25}
1
2 private static int getRandomNumberInRange(int min, int max)
3 {
4
5 if (min >= max) {
6 throw new IllegalArgumentException("max must be greater than min");
7 }
8
9 Random r = new Random();
10 return r.nextInt((max - min) + 1) + min;
11 }
12
13
14 //Random().nextInt(int bound) = Random integer from 0 (inclusive) to bound (exclusive)
15
16 //1. nextInt(range) = nextInt(max - min)
17 new Random().nextInt(5); // [0...4] [min = 0, max = 4]
18 new Random().nextInt(6); // [0...5]
19 new Random().nextInt(7); // [0...6]
20 new Random().nextInt(8); // [0...7]
21 new Random().nextInt(9); // [0...8]
22 new Random().nextInt(10); // [0...9]
23 new Random().nextInt(11); // [0...10]
24
25 //2. To include the last value (max value) = (range + 1)
26 new Random().nextInt(5 + 1) // [0...5] [min = 0, max = 5]
27 new Random().nextInt(6 + 1) // [0...6]
28 new Random().nextInt(7 + 1) // [0...7]
29 new Random().nextInt(8 + 1) // [0...8]
30 new Random().nextInt(9 + 1) // [0...9]
31 new Random().nextInt(10 + 1) // [0...10]
32 new Random().nextInt(11 + 1) // [0...11]
33
34 //3. To define a start value (min value) in a range,
35 // For example, the range should start from 10 = (range + 1) + min
36 new Random().nextInt(5 + 1) + 10 // [0...5] + 10 = [10...15]
37 new Random().nextInt(6 + 1) + 10 // [0...6] + 10 = [10...16]
38 new Random().nextInt(7 + 1) + 10 // [0...7] + 10 = [10...17]
39 new Random().nextInt(8 + 1) + 10 // [0...8] + 10 = [10...18]
40 new Random().nextInt(9 + 1) + 10 // [0...9] + 10 = [10...19]
41 new Random().nextInt(10 + 1) + 10 // [0...10] + 10 = [10...20]
42 new Random().nextInt(11 + 1) + 10 // [0...11] + 10 = [10...21]
43
44 // Range = (max - min)
45 // So, the final formula is ((max - min) + 1) + min
46
47 //4. Test [10...30]
48 // min = 10 , max = 30, range = (max - min)
49 new Random().nextInt((max - min) + 1) + min
50 new Random().nextInt((30 - 10) + 1) + 10
51 new Random().nextInt((20) + 1) + 10
52 new Random().nextInt(21) + 10 //[0...20] + 10 = [10...30]
53
54 //5. Test [15...99]
55 // min = 15 , max = 99, range = (max - min)
56 new Random().nextInt((max - min) + 1) + min
57 new Random().nextInt((99 - 15) + 1) + 15
58 new Random().nextInt((84) + 1) + 15
59 new Random().nextInt(85) + 15 //[0...84] + 15 = [15...99]
60
61 //Done, understand?
1import java.util.concurrent.ThreadLocalRandom;
2
3// nextInt is normally exclusive of the top value,
4// so add 1 to make it inclusive
5int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
6