Java: разрыв цикла - PullRequest
       10

Java: разрыв цикла

0 голосов
/ 23 февраля 2011

Каков наилучший способ реализовать следующий псевдокод в 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: Спасибо за быстрые ответы, всем. Очень помогло. Разобрался сейчас.

Ответы [ 3 ]

4 голосов
/ 23 февраля 2011

Если вам не нужны отдельные методы, это должно быть эквивалентно:

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
    }
}
3 голосов
/ 23 февраля 2011

Я думаю, вы могли бы сделать что-то вроде:

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
  }
}
0 голосов
/ 23 февраля 2011

Предполагая, что я правильно прочитал псевдокод, это довольно простой случай вызова методов. Единственный улов заключается в том, что все, что представляет условия один, два и три, должно быть где-то обновлено, или это будет бесконечный цикл в method_two (или 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
        }
    }
}
...