How can I generate a random number of whole characters in java
a = Math.random () * 25 + 1; System.out.println (Math.round (a)) // the 25 sets the limit
How can I generate a random number of whole characters in java
a = Math.random () * 25 + 1; System.out.println (Math.round (a)) // the 25 sets the limit
The method Random.nextInt (n) provide what you need, you can use it this way:
int aleatoreo(int vMin, vMax) {
Random r = new Random();
return vMin + r.nextInt(vMax - vMin + 1);
}
System.out.println(aleatorio(0,25));
It will generate a pseudo-random number between [ vMin
, vMax
] or [ 0
, 25
] in the example.
This method can help you;
public static int generarAleatorio(int min, int max){
Random random = new Random();
return random.nextInt(max-min+1)+min;
}
The first parameter min
being the number from where you want to start and max
the end.
I edit the answer according to the author's comments:
package numeros_aleatorios_enteros;
import java.util.Random;
public class Numeros_aleatorios_enteros {
public static void main(String[] args) {
System.out.println(generarAleatorio(1, 25));
}
public static int generarAleatorio(int min, int max){
Random random = new Random();
return random.nextInt(max-min+1)+min;
}
}
I just wanted to point out two things, since it would be convenient to have a function to do this operation.
min
, you will have a crash in the application, since the exception max
will be raised. Then that has to be avoided. java.lang.IllegalArgumentException: bound must be greater than origin
method was added % to class ints
, with which randoms can be generated more efficiently. Then I put a response by applying the two points mentioned. In this case, the returned value will be Random
when the value of -1
is greater than the value of min
. This can be changed, depending on the use that is going to be given to the method.
import java.util.Random;
class Rextester
{
public static void main(String args[])
{
System.out.println(getRandomInRange(0, 25));
System.out.println(getRandomInRange(250, 25));
System.out.println(getRandomInRange(1, 25));
System.out.println(getRandomInRange(0, 88));
System.out.println(getRandomInRange(1, 88));
/*Prueba controlando si min es mayor que max*/
int myRandom=getRandomInRange(50, 25);
if (myRandom==-1){
System.out.println("No se puedo generar un random");
}else{
System.out.println("Random generado: "+myRandom);
}
}
/*Función que se podría incorporar a una clase utilitaria*/
private static int getRandomInRange (int min, int max) {
int rValue = -1;
if (max>min) {
Random r = new Random();
rValue= r.ints(min, (max + 1)).limit(1).findFirst().getAsInt();
}
return rValue;
}
}
17
-1
12
19
54
No se puedo generar un random