Error with Random in JAVA

3

I get this exception, related to Random.

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
    at java.util.Random.nextInt(Random.java:388)
    at gestorgrupos.Grupo.opcionAleatoria(Grupo.java:78)
    at gestorgrupos.Generador.generarListaOpciones(Generador.java:125)
    at principal.Principal.main(Principal.java:77)

I leave below the code where the generation of the random number is, to see if someone finds some kind of anomaly, I think it's fine.

Random aleatoria = new Random();
 int i = aleatoria.nextInt(this.numGrupos);

-------------- I add the method ----------------

public String generarListaOpciones() {

    String texto = "";

    Random aleatoria = new Random();
    int i = aleatoria.nextInt(this.numGrupos);
    int j = 1;
    IElegible opcionAleato;

    texto += "Orden de las opciones:";

    while (this.numGrupos > 0) {
        opcionAleato = this.grupos[i].opcionAleatoria();
        String mensaje = opcionAleato.opcion();

        texto += "nº" + j + " - Grupo: " + this.grupos[i].nombreCompleto() + "Opción: - "
                + this.grupos[i].opcionAleatoria().opcion() + mensaje;
        this.grupos[i].eliminaOpcion(opcionAleato);

        if (this.grupos[i].opciones.length == 0) {
            int posicionFinal = numGrupos-1;
            this.grupos[i] = this.grupos[posicionFinal];
            this.numGrupos--;
        }
        j++;
    }
    return texto;
}

------------------ view from debugger -----------------------

    
asked by Carlos 11.05.2018 в 13:07
source

1 answer

6

In the documentation , as a curiosity , explicitly comments that the code of that method is equivalent to the following:

public int nextInt(int bound) {
   if (bound <= 0)
     throw new IllegalArgumentException("bound must be positive");

   if ((bound & -bound) == bound)  // i.e., bound is a power of 2
     return (int)((bound * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % bound;
   } while (bits - val + (bound-1) < 0);
   return val;
 }

So the problem is that this.numGrupos is a negative value or is zero, when it should be greater than zero.

    
answered by 11.05.2018 в 13:12