2015-11-20 35 views
-1

我有這樣的:從迴路斷開,當條件爲真

for(String s : names){ //names is an ArrayList of strings 

    if(s.equals("bob")){ 
     //do sth and then break from the loop 
     break; 
    } 

} 

當裏面的,如果是真的,我希望for循環打破了條件。但它不......我的代碼錯了嗎?

編輯:

的問題是,我有一個額外的for循環在我的代碼

for(//a loop here){ 
     for(String s : names){ //names is an ArrayList of strings 

      if(s.equals("bob")){ 
      //do sth and then break from the loop 
      break; 
      } 
     } 
    } 

這就是爲什麼裏面loop被突破後執行...

+1

確定'names'包含' 「鮑勃」'字符串? – Eran

+1

你確定它全是小寫嗎?使用'.equalsIgnoreCase'作爲不區分大小寫的字符串比較 – Arc676

+0

我投票結束,因爲我在代碼中有2個循環.. – yaylitzis

回答

1

代碼看起來不錯,您的列表中有一些數據問題或difference of case in two strings。嘗試使用equalsIgnoreCase而不是equals建議

它只是打印hi,只要bob它來休息。

public static void main(String[] args) { 
     List<String> names = new ArrayList<String>(); 
     names.add("hi"); 
     names.add("bob"); 
     names.add("bye"); 

     for (String s : names) { 
      if (s.equals("bob")) { 
       System.out.println("breaking..."); 
       break; 
      } else { 
       System.out.println(s); 
      } 
     } 
    } 

輸出

hi 
breaking... 
+0

ok我看到..我發現我的錯誤...我在代碼中有2個循環.. thx讓我清醒了.. – yaylitzis