[英]how to break an enhanced for loop from a switch in java
我发现了一件有趣的事情,您可以通过中断来中断增强循环。 陈述,但我想知道是否有可能从该语句内的switch语句中断增强的For循环
例如
String test = "(2.0+4.0)";
for (char now : test.toCharArray()){
switch (now) {
case '(':
// i want the loop to stop from this point
break;
case ')':
case '/':
case '*':
case '+':
case '-':
}
}
编辑
找到标记为中断的答案。 但是我要去老学校
String test = "(2.0+4.0)";
boolean found = false;
for (char now : test.toCharArray()){
switch (now) {
case '(':
// i want the loop to stop from this point
System.out.println(now);
found = true;
continue;
case ')':
case '/':
case '*':
case '+':
case '-':
}
System.out.println("im out of switch");
if(found)break;
}
System.out.println("out of Loop");
}
做到了
感谢所有的答案
您可以在for循环中添加标签,并在switch语句中将其断开。
public static void main (String args[]){
String test = "))(2.0+4.0)";
int i = 0;
labelLoop :
for (char now : test.toCharArray()){
switch (now) {
case '(':
break labelLoop;
case ')':
case '/':
case '*':
case '+':
case '-':
i++;
}
}
System.out.println(i);
}
这将打印2。
使用语句标签:
a: for (char now : test.toCharArray()){
switch (now) {
case '(':
break a;
case ')':
case '/':
case '*':
case '+':
case '-':
}
}
是的,具有以下语法:
label:
for (char now : array) {
switch(now) {
case '(':
break label;
}
}
这适用于Java中的各种循环。
您可以break
障碍:
the_block:
for (char now : test.toCharArray()){
switch (now) {
case '(':
break the_block;
// ...
}
}
也许有人对此语法感到困惑,许多人希望在break the_block;
标签后的所有内容都必须再次执行。 否。实际上, the_block
是以下块的名称。 break the_block;
不是goto the_block;
。 这意味着中断名为the_block
的块。 因此,通过破坏该块,您将期望控件脱离该块并正确。
为了更清楚一点,我在循环中加上了{}
:
the_block: {
for (char x : array){
switch (x) {
case '(':
break the_block;
// ...
}
}
而且,由于它不是goto/labal
机制,因此也不是坏习惯,所有内容都是清晰易读的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.