避免在 "break and not execute code after loop" 循环中使用 `goto`
Avoid `goto` in a loop with "break and not execute code after loop"
必须避免转到。但有些情况下你无法避免,没有丑陋的代码。
考虑这个案例:
当循环内的表达式为真时,循环必须中断。
如果循环内的表达式始终为假,则循环结束后,代码必须是运行。
有没有不用 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
}
块语句是一个语句,所以你可以给它一个标签。
必须避免转到。但有些情况下你无法避免,没有丑陋的代码。
考虑这个案例:
当循环内的表达式为真时,循环必须中断。
如果循环内的表达式始终为假,则循环结束后,代码必须是运行。
有没有不用 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
}
块语句是一个语句,所以你可以给它一个标签。