Mr. White
Mr. White

Reputation: 204

How can I generate two random numbers(not repeated)?

I want to generate two numbers in range 0..99 in java and it has to be not repeated. I tried code below but it is not working for me.

    int number1 = randomGenerator.nextInt(100);
    int number2 = randomGenerator.nextInt(100);

    if(number1 == number2){
        while (number1 != number2){
            number2 = randomGenerator.nextInt(100);
        }
    }

Upvotes: 1

Views: 203

Answers (4)

user184994
user184994

Reputation: 18281

If they all have to be unique, you should add the results to a list. Then, you can compare the current random number to each of the past results.

    Random random = new Random();
    int number1 = random.nextInt(100);
    int number2 = random.nextInt(100);
    List<Integer> randomsList = new ArrayList<Integer>();

    while (randomsList.contains(number1)){
        number1 = random.nextInt(100);
    }
    randomsList.add(number1);

    while (randomsList.contains(number2)){
        number2 = random.nextInt(100);
    }
    randomsList.add(number2);

Upvotes: 0

Nikolay
Nikolay

Reputation: 1949

int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(99);
if(number2 >= number1) {
  ++number2;
}

Also check discussion about it at Generate random index different then any one given in a set

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

It's not working because you never enter your loop, because the condition is wrong. In the loop, you want ==, not !=. You can also remove the if:

int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(100);

while (number1 == number2){
    number2 = randomGenerator.nextInt(100);
}

Upvotes: 1

Tobias
Tobias

Reputation: 7771

If number1 and number2 are equal, they will not be not equal. Just change your while loop:

int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(100);

while(number1 == number2){
    number2 = randomGenerator.nextInt(100);
}

Upvotes: 4

Related Questions