1

我想在 java 中生成 0..99 范围内的两个数字,并且不能重复。我尝试了下面的代码,但它对我不起作用。

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

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

4 回答 4

4

如果number1number2相等,它们将相等。只需更改您的while循环:

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

while(number1 == number2){
    number2 = randomGenerator.nextInt(100);
}
于 2013-11-03T10:51:24.610 回答
1

它不起作用,因为您从未进入循环,因为条件错误。在循环中,你想要==,而不是!=。您还可以删除if

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

while (number1 == number2){
    number2 = randomGenerator.nextInt(100);
}
于 2013-11-03T10:51:28.417 回答
0
int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(99);
if(number2 >= number1) {
  ++number2;
}

还要检查关于它的讨论生成随机索引不同于集合中给出的任何一个

于 2013-11-03T10:53:03.193 回答
0

如果它们都必须是唯一的,则应将结果添加到列表中。然后,您可以将当前随机数与过去的每个结果进行比较。

    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);
于 2013-11-03T11:07:55.780 回答