我似乎无法弄清楚为什么它允许重复通过。我认为我的代码意味着我不希望它有任何重复。现在我的代码的方式将向我的ArrayList添加7个随机数,这很好,但它也添加了重复,但不是。
import java.util.ArrayList;
import java.util.Random;
public class LotteryNumbers {
private ArrayList<Integer> numbers;
public LotteryNumbers() {
this.drawNumbers();
}
public ArrayList<Integer> numbers() {
Random randomizer = new Random();
int i = 1;
while (i <= 7) {
if (!numbers.contains(randomizer.nextInt(39 + 1))); {
numbers.add(randomizer.nextInt(39) + 1);
i++;
}
}
return this.numbers;
}
public void drawNumbers() {
this.numbers = new ArrayList<Integer>();
}
}
答案 0 :(得分:0)
修复您的numbers()
方法,如下所示
public ArrayList<Integer> numbers() {
Random randomizer = new Random();
int i = 1;
int num;
while (i <= 7) {
num = randomizer.nextInt(39 + 1);
if (!numbers.contains(num)); {
numbers.add(num);
i++;
}
}
return this.numbers;
}