2013-03-17 132 views
0

我想寫一個方法,將搜索名爲「項目」數組的索引,以查看是否包含多個索引相同的字符串(忽略大小寫) 。如果一個字符串不止一次位於數組中,該方法應輸出一條消息並退出。用我現在所擁有的,循環有時會起作用,有時候不起作用 - 例如,如果存儲了字符串「house」和「hOuse」,它將不會捕獲它,儘管它應該。我最初打破了;找到後= true;並認爲消除它可能會有所幫助,但事實並非如此。有什麼建議?創建一個方法來搜索數組索引重複值

public void equals() { 
    boolean found = false; 
    for (int i = 0; i < items.length; i++) { 
     for (int j = 1; j > i && j < items.length; j++) { 
      if (items[i].equalsIgnoreCase(items[j])) { 
       found = true; 
      } 
     } 
    } 
    if (found) { 
     System.out.println("You listed the same item more than once. Please restart and try again."); 
     System.exit(0); 
    } 
} 

回答

2

這是你的問題

for (int i = 0; i < items.length; i++) { 
     for (int j = 1; j > i && j < items.length; j++) { 

將其更改爲

for (int i = 0; i < items.length; i++) { 
     for (int j = i+1; j > i && j < items.length; j++) { 

推理:如果我是說2和j是1,J沒有立即>立即1和內環路回報。這顯然不是你想要的,因爲它意味着比較只會發生在數組中的第一個字符串上。

當然並且,因爲Ĵ現在總是>我,我們可以刪除檢查:

for (int i = 0; i < items.length; i++) { 
     for (int j = i+1; j < items.length; j++) { 

好多了。

順便說一句,您可以通過添加您的所有字符串的一個HashSet<String>http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html),並檢查您的HashSet VS您的原始集合的長度的長度讓你的算法非常快 - 如果它是較低的,有重複。這將會爲O運行(n日誌(n))的,而不是爲O(n^2)

+0

的HashSet不會管理不區分大小寫的部分... – assylias 2013-03-17 22:52:31

+0

@assylias插入的所有字符串:) – Patashu 2013-03-17 22:53:12

+0

+1也許沒有那麼重要音符的小寫版本,但在第二的,你可以將「J>時我「作爲j始終如一的方式來增加清晰度。 – 2013-03-17 22:53:34

1

你應該改變:

for (int j = 1; j > i && j < items.length; j++) 

for (int j = i + 1; j < items.length; j++) 

寫出更短和更簡單的方法方法是:

public void equals() { 
    Set<String> set = new TreeSet<String> (String.CASE_INSENSITIVE_ORDER); 
    set.addAll(Arrays.asList(items)); 
    if (set.size() != items.length) { 
     System.out.println("You listed the same item more than once. Please restart and try again."); 
    } 
} 

最後,讓你的方法可重複使用的,你可以寫這樣的:

public boolean hasDuplicatesIgnoreCase(String[] items) { 
    ... 
    return true/false; 
} 
+0

完美的作品。非常感謝! – user2180462 2013-03-18 14:24:13