2011-03-25 26 views
-2

我有兩個字符串數組比較兩個字符串數組來檢查輸入的值是有字符串數組中

String[] Mids contains 
MSI 
MSU 
MSV 

String[] sl contains 
    MSU 
    MSV 
    MSS 

實際產量應該是

Action 
Action 
Action cannot be set 

for(int i=0;i<sl.length;i++){ 
       for(int j=0;j<Mids.length;j++){ 
        if((sl[i].equals(Mids[j]))){ 
         System.out.println("Action"); 
        }else{ 
         System.out.println("Action cannot be set"); 
        } 
       } 
      } 

輸出,我得到

Action cannot be set 
Action cannot be set 
Action cannot be set 
Action cannot be set 
Action 
Action cannot be set 
Action 
Action cannot be set 
Action cannot be set 
+3

現在大家都預期)來找出你真的很想,b)你失敗的地方,以及c)如何解決它?你如何給我們提供關於你想要完成什麼(以及爲什麼)的更多細節。 – Bombe 2011-03-25 08:21:13

+0

你是否被迫使用數組?什麼地方出了錯? – 2011-03-25 08:32:23

回答

4

問題是你正在遍歷這兩個數組,並始終打印,如果你找到了相同的值。但是你只能在第一個循環中這樣做。我改變了對循環:

for(int i=0;i<sl.length;i++){ 
    boolean found = false; 
    for(int j=0;j<Mids.length;j++){ 
     if((sl[i].equals(Mids[j]))){ 
     found = true; 
     break; 
     } 
    } 

    if (found) { 
     stdOut.println("Action"); 
    } else { 
     stdOut.println("Action cannot be set"); 
    } 
} 
0

你爲什麼不添加下的for循環(我)另一個打印線顯示S1和MID,這樣就可以更好地理解執行?

1

要說如果在數組中找不到元素,您需要將它與所有元素進行比較。僅僅因爲一次比較失敗,你不能斷定它在數組中找不到。

試着這麼做:

for(int i=0;i<sl.length;i++){ 
     boolean found = false; 
     for(int j=0;j<Mids.length;j++){ 
       if((sl[i].equals(Mids[j]))){ 
         found = true; 
         break; 
       } 
     } 
     if(found) { 
       // print found. 
     } else { 
       // print not found.            
     } 
} 
0

另一種方式來做到這一點,用更少的代碼和更少的迭代是:

List<String> midsList = new ArrayList<String>(Arrays.asList(Mids)); 
    for (String string : sl) { 
     if (midsList.contains(string)) { 
      System.out.println("Action"); 
     } else { 
      System.out.println("Action cannot be set"); 
     } 
    }