EN
Java - random integer number in range with exclusive max value example
4 points
In this short article we want to show how in Java randomize integer number in range with exclusive max value.
xxxxxxxxxx
1
package com.dirask.examples;
2
3
public class RandomUtil {
4
5
public static int randomize() throws Exception {
6
return randomize(Integer.MAX_VALUE);
7
}
8
9
public static int randomize(int max) throws Exception {
10
return randomize(0, max);
11
}
12
13
public static int randomize(int min, int max) throws Exception {
14
if(min > max - 1) {
15
throw new Exception("Incorrect arguments.");
16
}
17
return (int) (min + (max - min) * Math.random());
18
}
19
}
Usage example:
xxxxxxxxxx
1
package com.dirask.examples;
2
3
public class Program {
4
5
public static void main(String[] args) throws Exception {
6
7
System.out.println( RandomUtil.randomize() ); // 5547382624322139
8
System.out.println( RandomUtil.randomize( 5 ) ); // 3
9
System.out.println( RandomUtil.randomize( 10, 80 ) ); // 62
10
System.out.println( RandomUtil.randomize(-50, 50 ) ); // -8
11
}
12
}