2015-11-20 22 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