我目前正在研究Java并且到目前为止正在使用普通数组。下学期我们将使用像ArrayList等数据结构,但我决定提前阅读。我已经读过,为了存储不能重复的数据,集合是首选的数据结构,但在下面的代码中,用户仍然可以输入重复的条目?任何机构都可以向我解释这个过程,也许可以解决我的问题吗?
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 0;
private static final int MAX_NUMBER_POSSIBLE = 25;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Pick " + INPUT_SIZE + " numbers from "
+ MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ".");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("You win :) !");
} else {
System.out.println("Sorry you failed :( !");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nRandom numbers where : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChoosen = input.nextInt();
if (numberChoosen < MIN_NUMBER_POSSIBLE
|| numberChoosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in "
+ MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE
+ " range.");
} else {
userNumbers.add(numberChoosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been called.");
}
}
答案 0 :(得分:2)
Set#add(Object)
会返回true
,否则会返回false
。它不会抛出异常,因此您需要添加条件以检查操作是否成功:
if (userNumbers.add(numberChoosen)) {
System.out.println("Number added successfully");
} else {
System.out.println("Duplicate number detected");
}
答案 1 :(得分:1)
设置不禁止多次输入唯一值。您可以检查前置条件,例如Set.add。
所以不要只是打电话:
userNumbers.add(numberChoosen);
试
if (!userNumbers.contains(numberChoosen)) {
userNumbers.add(numberChoosen);
} else {
// do stuff...
}