2012-10-06 18 views
0

基本上我希望它停止並打印一條消息,如果他們已經將該人員添加到ArrayList中,但它不會那樣做。爲什麼我的equals方法在這個類中不起作用?它不能正常工作

這裏的方法:

@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."); 
        } 
       } 
      } 
     } 
    } 

我辛苦在這個很長一段時間,但不能把我的手指上爲什麼將無法工作。

+0

請參閱[本文](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)以獲取如何比較Java中的字符串的詳細說明。 – assylias

回答

1

使用equals()方法來比較字符串,而不是==

1

你也應該在你的Student.equals方法使用String.equals

if (this.getName().equals(((Student) o).getName()) && 
    this.getID().equals(((Student)o).getID())) 

Student.equals使用==String比較,比較的對象引用,如果Strings按字典順序相等,則會失敗,但不會是相同的String對象。

0

。在你的equals方法問題..

public boolean equals(Object o) { 
    if (this.name == ((Student)o).getName() && this.ID == ((Student)o).getID()) { 
      return true; 
    } 
    else { 
      return false; 
    } 
} 

你應該使用equals()方法,這也name比較..

this.name.equals(((Student)o).getName()) 

如果你的ID也是一個字符串,這樣做因爲它也..

0

使用equals比較名稱和ID的。在這種情況下,==比較歸結爲一個對象的comaration,將導致錯誤,因爲兩個名稱(每個不同String)是不同的對象。它不會進行字面比較。

爲防萬一,由於是名稱比較,因此您可能需要使用equalsIgnoreCase,因爲例如John Doe本質上與john doe的名稱基本相同。如果ID是字母數字,則也是如此。

相關問題