The method Math#random
returns a double equal to or greater than 0.0 and less than 1.0 .
int numeroAleatorio = (int) (1000 + Math.Random() * 10000);
One of the problems of the code is that the minimum value is not indicated, instead the maximum value is multiplied by the value of Math.Random
, which can be for example: 0.02 or 0.98 , then the minimum value is added.
The correct one would be to subtract the maximum and minimum value and add 1 (if you want the maximum value to be returned randomly), then multiply by the value of Math.random
, finally, just add the minimum value to indicate the beginning of the interval.
public static int numeroAleatorio(int a, int b) {
final int min = Math.min(a, b);
final int max = Math.max(a, b);
return min + (int)(Math.random() * ((max - min) + 1));
}
The casting for
int
is required to truncate the result (due to
Math.random
returning a
double
). >
If you prefer to use Random#nextInt-int
instead of Math#random
:
public static int numeroAleatorio2(int a, int b) {
final int min = Math.min(a, b);
final int max = Math.max(a, b);
Random r = new Random();
return min + r.nextInt((max - min) + 1);
}
To use, just do the following:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(numeroAleatorio(1000, 9999));
}
See DEMO