Can a LABEL block be used without loop? Any examples?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here is an example of using labels and break statements without a loop:
block1: {
if (a < 0) {
break block1;
}
if (b < 0) {
break block1;
}
return a + b;
}
回答2:
But why use a label on a code block?
My application is usually a switch on a String variable (or anything other than char, byte, short, int, Enum).
"To make an omelette, you have to break some eggs"
Example:
String key = "scrambled";
eggs: {
if ("do-nothing".equals(key)) break eggs;
if ("scrambled".equals(key)) {
;//scramble code here
break eggs;
}
if ("fried".equals(key)) {
;//fry code here
break eggs;
}
//default behaviour goes here
//or maybe throw an exception
}
Ok, ok, "Sometimes, to make an omelette, you have to kill a few people"
Alternatives:
- Java 7 allows String as the switch.
- An Enum workaround using MyEnum.valueOf(str) can be made to work.
- A switch on the String (or
Object)'s hashcode plus some more
if-then-else if
is possible but would only make sense for lots of possibilities, in which case the whole thing is probably due for an overhaul.
回答3:
public static void main(String[] args)
{
hello: break hello;
}
回答4:
certainly:
private boolean isSafe(String data) {
validation: {
if (data.contains("voldemort")) {
break validation;
}
if (data.contains("avada")) {
break validation;
}
if (data.contains("kedavra")) {
break validation;
}
return true;
}
return false;
}
@DragonBorn: that's not possible. You can only continue or break a label from within it's scope, for example:
label1: for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.println(i + " " + j);
if (i == j) {
continue label1;
}
}
}
produces:
0 0
1 0
1 1
2 0
2 1
2 2
3 0
3 1
3 2
3 3
回答5:
If you want some unreadable code:
int i = 1;
int j = 1;
label: switch (i) {
case 1:
switch (j) {
case 1:
break label;
}
default:
System.out.println("end");
}
Without break;
will print "end". break label;
will skip the print.