The following code example shows how to generate a random number within a range for int, long, float and double (inclusive means the max value is included for int and long):
int min = 122;
int max = 134;
SecureRandom rnd = new SecureRandom();
int inclusive = max - min + 1;
int exclusive = max - min;
int rndIntIncl = rnd.nextInt(inclusive) + min;
int rndIntExcl = rnd.nextInt(exclusive) + min;
System.out.println("Integer (incl.): " + rndIntIncl);
System.out.println("Integer (excl.): " + rndIntExcl);
long rndLongIncl = ( Math.abs(rnd.nextLong()) % inclusive ) + min;
long rndLongExcl = ( Math.abs(rnd.nextLong()) % exclusive ) + min;
System.out.println("Long (incl.): " + rndLongIncl);
System.out.println("Long (excl.): " + rndLongExcl);
float rndFloat = ( rnd.nextFloat() * exclusive ) + min;
System.out.println("Float : " + rndFloat);
double rndDouble = ( rnd.nextDouble() * exclusive ) + min;
System.out.println("Double : " + rndDouble);
Integer (incl.): 129 Integer (excl.): 130 Long (incl.): 125 Long (excl.): 127 Float : 125.42884 Double : 127.84922531497857
No comments:
Post a Comment