我想在java中生成两个数字,范围为0..99,并且不得重复。我试过下面的代码,但它对我不起作用。
int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(100);
if(number1 == number2){
while (number1 != number2){
number2 = randomGenerator.nextInt(100);
}
}
答案 0 :(得分:4)
如果number1
和number2
相等,则不相等。只需更改while
循环:
int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(100);
while(number1 == number2){
number2 = randomGenerator.nextInt(100);
}
答案 1 :(得分:1)
它不起作用,因为你从不进入循环,因为条件错误。在循环中,您需要==
,而不是!=
。您也可以删除if
:
int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(100);
while (number1 == number2){
number2 = randomGenerator.nextInt(100);
}
答案 2 :(得分:0)
int number1 = randomGenerator.nextInt(100);
int number2 = randomGenerator.nextInt(99);
if(number2 >= number1) {
++number2;
}
同时在Generate random index different then any one given in a set
检查有关它的讨论答案 3 :(得分: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);