2014-02-12 55 views
1

我們被要求創建一個能夠添加,編輯和搜索數據的學生和教師目錄。在搜索部分,我的老師要求一個輸出,它將顯示與搜索中的輸入相匹配的所有結果。如何在java中搜索?

輸出樣本:

search name: ab 

output: 
1. **ab**a, josep jr v. [IV - Garent] 
2. **ab**acada, willie f. [III - Waling2x] 
3. **ab**zal, louie b. [i - Mercury] 


Press the number for details. Zero(0) back to the menu. 
Press you choice: 

我怎麼可以做這樣輸出的搜索?

我已經有

public void search(){ 
    System.out.print("search name : "); 

    try { 
     searchName = reader.readLine(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 


    searchCount = 0;//for search 

    for(int i = 0; i<count; i++){ 

     if(personList.get(i).getName().equals(searchName)){//for search 
      searchCount = i; 
      break; 
     } 

    } 

    System.out.println(personList.get(searchCount).getName() +" "+ personList.get(searchCount).getAge()); 

} 

String searchName = "";//for search, store search name 
int searchCount = 0;//for search 
+2

使用'contains',而不是'equals'的搜索 – BackSlash

回答

0

當你搜索次數=我;您應該保存在列表中找到的對象,然後打印出列表,或者直接打印出項目。

for(int i = 0; i<personList.size(); i++){ 
     if(personList.get(i).getName().contains(searchName)){ 
      System.out.println(personList.get(i).getName() +" "+ personList.get(i).getAge()); 
     } 
    } 

List<person> resultSet = new ArrayList<person>(); 
    for(int i = 0; i<personList.size(); i++){ 
     if(personList.get(i).getName().contains(searchName)){ 
      resultSet.add((personList.get(i)) 
     } 
    } 

    for(int i = 0; i<resultSet.size(); i++){ 
     System.out.println((i+1) + ". " + resultSet.get(i).getName() +" "+ resultSet.get(i).getAge()); 
    } 
+0

什麼,如果它這樣 輸出樣本: 搜索名稱:克魯茲 輸出: 1.克魯茲,拉斐爾·F。 [III - Waling2x] 2. cruztana,marry b。 [我 - 水星] 3. dela cruz,rofina p。 [IV - Garent] – murrmurr

+0

創建此示例輸出的問題是什麼?我可以給你一個例子,但我不知道,你需要得到您想要打印 – kai

+0

用戶搜索詞的信息的方法「克魯茲,再有就是有兩個詞(德拉克魯茲),這名稱應的名稱在因爲第二個字的單詞「克魯茲」 – murrmurr

0

使用String#contains(String)而不是String#equals(Object)

0

更改這行代碼中爲::

  if(personList.get(i).getName().contains(searchName)){ 
      //for search 

java.lang.String.contains()方法返回true,當且僅當此字符串包含char值的指定序列。

String.equals的字符串指定的對象進行比較。當且僅當參數不爲null並且是表示與此對象相同字符序列的String對象時,結果爲true。