0

This is what I am going to do. I want to generate random numbers between -1 and 1. Then I add that generated number to a specific number. I want to continue this until that total value reaches another specific value.

int distance = 5;
int min = -1;
int max = 1;
int randomValue;


   while(distance <= 10){
       randomValue = (int)(Math.random()*(max-min+1)+min);
       distance = randomValue + distance;
       Log.d("Output", "value is"+distance);
   }

This returns values up to 11. how can I resolve this

WCM
  • 595
  • 3
  • 11
  • 27

3 Answers3

2

Your condition should be:

while(distance != 10) {
    // ...
}

With your current condition, you run the risk of adding one even when distance is already at 10.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

You can try this,

public int getRandomNumberUsingInts(int min, int max) {
    Random random = new Random();
    return random.ints(min, max)
      .findFirst()
      .getAsInt();
}

If you put max 2 and min -1, the randomly generated number will have 3 possibilities, They are: -1, 0, 1

daysling
  • 118
  • 10
1

You can use ThreadLocalRandom.current().nextInt(-1,2); for your requirement. This will generate random numbers between -1 and +1. So the loop reads as,

    while(distance <= 10){
       randomValue = ThreadLocalRandom.current().nextInt(min,max+1);
       distance = randomValue + distance;
       Log.d("Output", "value is"+distance);
   }

Only catch is that you'll need to increment max by 1 since the upper bound is exclusive.

Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35