简体   繁体   中英

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);
        }
    }

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);
}

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);
}
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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM