Generate random data within a range

2

I can not return any number. Ex: If you use "minor 1500" and "greater 5000", it was to appear in this range if you did not enter while , only it is not returning anything.

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;
}
    
asked by anonymous 14.03.2015 / 20:03

2 answers

11

Make use of what's already done ( Random ) and be happy. It works better and gives less work:

public int aleatoriar(int minimo, int maximo) {
    Random random = new Random();
    return random.nextInt((maximo - minimo) + 1) + minimo;
}

See running on ideone .

But if your problem does not need a random number in fact and you want to insist on its form:

public int aleatoriar(int minimo, int maximo) {
    Calendar lCDateTime = Calendar.getInstance();
    return (int)(lCDateTime.getTimeInMillis() % (maximo - minimo + 1) + minimo);
}

See running on ideone .

    
14.03.2015 / 20:45
3

You are not changing the return value, as it does not change the value of receive, to change it should change the while to the following:

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

Then you will not create an infinite loop.

    
14.03.2015 / 20:22