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 problem with the code is that the minimum value is not specified, instead the maximum value is multiplied by the value of Math.Random
, which may be for example: 0.02 or 0.98, then add the minimum value.
The correct 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));
}
Note: The casting for int
is necessary to truncate the result (due to the Math.random
return 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 so:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(numeroAleatorio(1000, 9999));
}
See DEMO
Can you put your code as text anyway? It’s bad for people to help this way. I myself didn’t feel like answering because I couldn’t use the code to test the solution I would give.
– Maniero