基本上,如果他们已经将该人添加到 ArrayList 中,我希望它停止并打印一条消息,但它不会那样做。
这是方法:
@Override
public boolean equals(Object o) {
if (this.name == ((Student)o).getName() && this.ID == ((Student)o).getID()) {
return true;
}
else {
return false;
}
}
以及它用于的代码部分:
public void addStudents() {
Scanner keyboard = new Scanner(System.in);
String name = "", ID = "";
System.out.println("Welcome! Please type exit at any point to stop entering students and for the lottery to commence.\n");
System.out.print("Student name: ");
name = keyboard.nextLine();
if (!name.equals("exit")) {
System.out.print("Student ID: ");
ID = keyboard.nextLine();
}
while (!name.equals("exit") && !ID.equals("exit")) {
System.out.print("\nStudent name: ");
name = keyboard.nextLine();
if (!name.equals("exit")) {
System.out.print("Student ID: ");
ID = keyboard.nextLine();
if (!ID.equals("exit")) {
boolean contains = false;
for (int i = 0; i < students.size(); i++) {
if (students.get(i).equals((new Student(name, ID)))) {
contains = true;
}
}
if (!contains) {
students.add(new Student(name, ID));
}
else {
System.out.println("You can only enter once.");
}
}
}
}
}
我已经为此苦苦挣扎了一段时间,但无法弄清楚为什么它不起作用。