2013-03-25 93 views
0

我做了三個類的聯繫人列表,ContactList類包含一個存儲姓氏,名字,街道,城市,州,郵政編碼,國家,電子郵件,電話號碼和筆記。按姓氏搜索數組

我想通過姓氏到ContactList的類實現一個搜索功能,它顯示了所有的聯繫人的姓氏用戶搜索,但我似乎無法得到任何工作。 :(

import java.util.*; 

public class ContactList { 

    //declaration of an array and its attributes 
    private final int SIZE = 10; 
    private Person [ ] list; 
    private int nextEmptyElementInArray = 0; 

    // Constructor for ContactList object 
    public ContactList() { 
     list = new Person [SIZE]; 
    } 

    // Method that adds a new contact into the array 
    public void addNewContact() { 
     list[nextEmptyElementInArray] = new Person(); 
     list[nextEmptyElementInArray].read(); 
     nextEmptyElementInArray++; 
    } 

    // Method retrieves contacts by last name 

    int searchByLastName(Person [] list) { 
     Scanner console; 
     console = new Scanner(System.in); 
     String searchByLastName = console.next(); 
     for (int i= 0; i< list.length; i++) { 
      if (list[nextEmptyElementInArray].lastName.equals(searchByLastName)) 
       return i; 
      } 
      return -1; 
     } 
    } 
+1

爲什麼你總是檢查'list [nextEmptyElementInArray]'?似乎應該是'list [i]'。 – 2013-03-25 01:23:56

回答

2

list標看來是錯誤的:在每個循環迭代你這樣做:

if (list[nextEmptyElementInArray].lastName.equals(searchByLastName)) 

如果我理解正確的問題,你應該這樣做:

if (list[i].lastName.equals(searchByLastName)) 

同時,應注意有關命名您的變量一樣的功能。充其量,它會引起混亂。

[編輯]只注意到你預先分配了列表,然後使用nextEmptyElementInArray管理實際內容長度。你for循環或許應該去像這樣:

for (int i= 0; i< nextEmptyElementInArray; i++) 
0

我建議改變搜索方法

int searchByLastName(Person [] list, String lastName) { 
     for (int i= 0; i < list.length; i++) { 
      if (list[i].lastName.equals(lastName)) 
       return i; 
      } 
     } 
     return -1; 
    } 

從控制檯讀取lastName的這一功能之外,把它作爲一個搜索PARAM