blackened
blackened

Reputation: 387

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.

Upvotes: 0

Views: 954

Answers (3)

justkt
justkt

Reputation: 14776

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
        }
    }
}

Upvotes: 0

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30999

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
    }
}

Upvotes: 4

jwir3
jwir3

Reputation: 6219

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
  }
}

Upvotes: 3

Related Questions