Java: Breaking Loop
What is the best way to implement the following pseudo-code in java?
method_one():
while(condition_one):
EXECUTE method_two(); // (A)
method_two():
while(condition_two):
EXECUTE method_three(); // (B)
method_three():
开发者_开发百科 if (condition_three):
GOTO EXECUTE method_two();
else:
//do some stuff
Edit: Thanks for prompt replies, everybody. Helped a lot. Figured it out now.
If you don't need separate methods, this should be equivalent:
boolean exit_from_three = false;
while (condition_one || exit_from_three) {
exit_from_three = false;
while (condition_two) {
if (condition_three) {exit_from_three = true; break;}
// do some stuff
}
}
I think you could do something like:
public void method_one() {
while (condition_one) {
method_two();
}
}
public void method_two() {
while (condition_two) {
method_three();
}
}
public void method_three() {
if (condition_three) {
return;
} else {
// do something magical
}
}
Assuming I've read the pseudo-code right, it's a pretty simple case of calling methods. The only catch is that whatever represents conditions one, two, and three have to be updated somewhere or this will be an infinite loop at method_two (or method_one).
public class LoopingClass {
private void method_one() {
while(/* condition_one, where condition_one results in a boolean value */) {
method_two();
}
}
private void method_two() {
while(/* condition_two, where condition_two results in a boolean value */) {
method_three();
}
}
private void method_three() {
if(/* condition_three - where condition_three results in a boolean value */) {
return;
} else {
// other stuff here
}
}
}
精彩评论