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.
1. Custom random method examples
package com.dirask.examples;
public class RandomUtil {
public static int randomize() throws Exception {
return randomize(Integer.MAX_VALUE);
}
public static int randomize(int max) throws Exception {
return randomize(0, max);
}
public static int randomize(int min, int max) throws Exception {
if(min > max - 1) {
throw new Exception("Incorrect arguments.");
}
return (int) (min + (max - min) * Math.random());
}
}
Usage example:
package com.dirask.examples;
public class Program {
public static void main(String[] args) throws Exception {
System.out.println( RandomUtil.randomize() ); // 5547382624322139
System.out.println( RandomUtil.randomize( 5 ) ); // 3
System.out.println( RandomUtil.randomize( 10, 80 ) ); // 62
System.out.println( RandomUtil.randomize(-50, 50 ) ); // -8
}
}