2017-01-27 25 views
-1

我需要幫助創建一個方法來查找數組中的對象並創建一個循環來更改對象。創建int find方法來查找數組中的對象

public void changeABFF() { 
    System.out.println("Enter first and the last name of the best friend you would like to change: "); 
    String fname = keyboard.next(); 
    String lname = keyboard.next(); 
    BestFriends other = new BestFriends(fname,lname,"",""); 

    boolean found = false; 
    for(int i=0;i<myBFFArray.length && found == false;i++) { 
     if(other.equals(myBFFs.get(i))) { 
      found = true; 
      System.out.println("Enter a First Name: "); 
      String fName = keyboard.next(); 
      System.out.println("Enter a Last Name: "); 
      String lName = keyboard.next(); 
      System.out.println("Enter a Nick Name: "); 
      String nName = keyboard.next(); 
      System.out.println("Enter a phone number"); 
      String cPhone = keyboard.next();  

      BestFriends tmp = myBFFs.get(i); 
      tmp.firstName = fName; 
      tmp.setLastname(lName); 
      tmp.setNickName(nName); 
      tmp.setCellPhone(cPhone); 
     } 
    } 
} 

所以我從數組列表更改爲陣,並更名爲myBFFArray

我的問題,是我該如何創建一個find方法對用戶輸入匹配到值數組中?

回答

0

您可以編輯BestFriends類重寫equals和hashCode比較兩個BestFriends對象

public class BestFriends { 

     private String firstName; 
     private String lastName; 
     private String nickName; 
     private String cellPhone; 

public BestFriends(String firstName, String lastName, String nickName, String cellPhone) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.nickName = nickName; 
     this.cellPhone = cellPhone; 
    } 

     public String getFirstName() { 
      return firstName; 
     } 

     public void setFirstName(String firstName) { 
      this.firstName = firstName; 
     } 

     public String getLastName() { 
      return lastName; 
     } 

     public void setLastName(String lastName) { 
      this.lastName = lastName; 
     } 

     public String getNickName() { 
      return nickName; 
     } 

     public void setNickName(String nickName) { 
      this.nickName = nickName; 
     } 

     public String getCellPhone() { 
      return cellPhone; 
     } 

     public void setCellPhone(String cellPhone) { 
      this.cellPhone = cellPhone; 
     } 

     @Override 
     public int hashCode() { 
      return this.hashCode(); 
     } 

     @Override 
     public boolean equals(Object obj) { 
      BestFriends bf = (BestFriends) obj; 

      return bf.getFirstName().equals(firstName) && bf.getLastName().equals(lastName) && bf.getNickName().equals(nickName) && bf.getCellPhone().equals(cellPhone); 
     } 

後,當你迭代這個數組

public BestFriends find(String firstName, String lastName, String nickName, String cellPhone) { 
     BestFriends bestFriends = new BestFriends(firstName, lastName, nickName, cellPhone); 

     for (BestFriends b: myBFFArray) { 
      if (b.equals(bestFriends)) { 
       return b; 
      } 
     } 
    }