Generate random data within a range

Asked

Viewed 10,600 times

3

I cannot return any number. Ex: If I use "lower 1500" and "higher 5000", I would appear in this interval if I did not enter the while, only nothing is returning.

public int aleatoriar(int maior, int menor) {   
    int retorno = 0;
    Calendar lCDateTime = Calendar.getInstance();
    int datarecebe = (int) (lCDateTime.getTimeInMillis());  
    int recebe = datarecebe % 10000;

    if (recebe > maior || recebe < menor) {
        while(recebe >= maior && recebe <= menor) {
            retorno = recebe;
        }
    } else {
        retorno = recebe;
    }       
    return retorno;
}
  • Dude, you’re not changing the receipt, how to change the return?

  • 4

    If you want to generate a random number, is there any reason not to use what Java has ready? Because what you’re doing isn’t exactly random.

  • Is there a strong reason not to use language packs !?

3 answers

13


Make use of what is already ready (Random) and be happy. It works better and takes less work:

import java.util.*;

class Main {
    public static void main (String[] args) {
        System.out.println(aleatoriar(1500, 5000));
    }
    public static int aleatoriar(int minimo, int maximo) {
        Random random = new Random();
        return random.nextInt((maximo - minimo) + 1) + minimo;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

But if your problem does not need a random number of fact and want to insist on its shape:

import java.util.*;

class Main {
    public static void main (String[] args) {
        System.out.println(aleatoriar(1500, 5000));
    }
    public static int aleatoriar(int minimo, int maximo) {
        Calendar lCDateTime = Calendar.getInstance();
        return (int)(lCDateTime.getTimeInMillis() % (maximo - minimo + 1) + minimo);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • you can explain to me what 'lCDateTime.getTimeInMillis()' does in the code.

  • 1

    @Rodolfo is taking the time from the machine. For what you want in the other question you don’t need it, just use the example from above. In fact it can even simplify, because when you start at 0 you don’t need this business of minimo and maximo, this is done to shift the initial number that is not required for you.

4

You are not changing the return value because you do not change the receive value, to change it you should change the while to the following:

while(recebe >= maior && recebe <= menor) {
    datarecebe = (int) (lCDateTime.getTimeInMillis());
    recebe = datarecebe % 10000;
    retorno = recebe;
}

Then yes you will not create an infinite loop.

0

From Java 7 you should use Threadlocalrandom

According to Effective Java, third edition, page 268:

From Java 7 you should no longer use Random. For most uses, the preferred random number generator is Threadlocalrandom. This class produces higher quality random numbers, and is very fast.

Consequently, the suggested code is

/**
 * Gera número pseudo-aleatório na faixa fornecida.
 *
 * @param primeiro O primeiro valor da faixa.
 * @param ultimo O último valor da faixa.
 * @return Um número contido na faixa indicada, incluindo os limites.
 *
 * @throws IllegalArgumentException Se a faixa for inválida, ou seja, o
 * valor {@code ultimo} é menor que o {@code primeiro}.
 */
public static int aleatorioNaFaixa(final int primeiro, final int ultimo) {
    Random rnd = ThreadLocalRandom.current();
    return rnd.nextInt(ultimo - primeiro + 1) + primeiro;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.