必须避免使用。但是在某些情况下,如果没有丑陋的代码,您就无法避免它。
考虑这种情况:
当循环中的表达式为真时,循环必须断开。
如果在循环结束后内部循环中的表达式总是错误的,则必须运行代码。
没有Goto的好方法?
for (int x = 0; x < input.length; ++x)
if (input[x] == 0) goto go_here; // this is pseudocode. goto is not allowed in java
// execute code
go_here:
我的解决方案是:
both:
do {
for (int x = 0; x < input.length; ++x)
if (input[x] == 0) break both;
// execute code
} while(false);
另一个解决方案是:
boolean a = true;
for (int x = 0; x < input.length; ++x)
if (input[x] == 0) { a = false; break; }
if (a) {
// execute code
}
另一个低效的解决方案(类似于goto(是:
try {
for (int x = 0; x < input.length; ++x)
if (input[x] == 0) throw new Exception();
// execute code
} catch(Exception e) {}
将您的病情放在方法中:
void yourMethod() {
if (yourCondition(input)) {
// execute code.
}
}
boolean yourCondition(int[] input) {
for (int i : input) {
if (i == 0) return false;
}
return true;
}
或,如果要使用IntStream
:
if (IntStream.of(input).noneMatch(i -> i == 0)) {
// execute code.
}
这是另一个解决方案:
both: {
for (int x = 0; x < input.length; ++x)
if (input[x] == 0) break both;
// execute code
}
块语句是一个语句,因此您可以给它一个标签。