2013-11-14 21 views
0
String searchValue;  
    boolean found = false; 
    int index = 0; 

    System.out.println("Enter a name to search for in the array."); 
    searchValue = kb.nextLine(); 

    while (found == false && index < names.length) { 
     if (names[index].indexOf(searchValue) != -1) { 
      found = true; 
     } else { 
      index++; 
     } 
    } 
    if (found) { 
     System.out.println("That name matches the following element:"); 
     System.out.println(names[index]); 
    } else { 
     System.out.println("That name was not found in the array."); 
    } 

就像標題所說的那樣,這隻產生第一個匹配,而不是數組中的所有匹配。我將如何改變它以顯示所有匹配?Java - 搜索數組只產生第一個匹配並且不是全部匹配

+0

因爲一旦找到匹配,該變量設置爲true,並且當條件不滿足從而跳過剩餘的比賽 – user1339772

回答

0

刪除這部分並思考整個算法。你必須重新考慮它。

if(names[index].indexOf(searchValue) != -1) 
{ 
    found = true; 
} 

它給你只有第一個原因是,您將發現真實和Java不會在之後while循環去。

+0

我明白了,但我不明白如何確定一場比賽而不會發現變爲真實。 if語句後應該重置爲false嗎? – user2993639

0

不是通過將找到的標誌設置爲true來終止循環,而是應該將結果添加到第二個數組中,該數組保存所有匹配並繼續下一次迭代,直到到達結尾。

0

你第一場比賽後,退出你的循環被發現 - 這個怎麼樣:

while (index < names.length) { 
     if (names[index].indexOf(searchValue) != -1) { 
      System.out.println("That name matches the following element:"); 
      System.out.println(names[index]); 
      found = true; 
     } else { 
      index++; 
     } 
    } 

    if (!found) { 
     System.out.println("That name was not found in the array."); 
    }