6

这就是我将如何做一个while循环:

boolean more = true;
while (more)
{
  // do something
  if (someTest()) 
  {
    more = false;
  }
}

这很标准。我很想知道是否有一种方法可以在 Java 中执行类似于以下代码的操作:(我想我已经在 C 中看到过类似的东西)

// The code below doesn't compile (obviously)
while (boolean more = true)
{
  // do something
  if (someTest())
  {
    more = false;
  }
}

我只问这个是因为目前我不喜欢在循环范围之外定义条件中使用的变量(在本例中为“更多”)的方式,即使它只在循环内部相关。循环结束后,它没有任何意义。


* * 更新 * *

参观 Porcaline 密室后,我想到了一个主意:

for (boolean more=true; more; more=someTest())
{
  // do something
}

它并不完美;它滥用了 for 循环,我想不出至少执行一次循环的方法,但它很接近......有没有办法确保循环执行 1 次以上?

4

3 回答 3

9

要从字面上回答您的问题,您可以这样做

for(boolean more = true; more; ) {
   more = !someTest();
}

但这与

while(!someTest());

如果它必须至少执行一次你可以做

do {

} while(!someTest());
于 2012-08-02T17:36:12.337 回答
1

对于您的具体情况,您可以将代码简化为:

while (true) {
  if (someTest()) {
    break;
  }
}

通常,您可以将外部范围声明替换为内部范围声明,但您需要移动循环条件:

while (true) {
  boolean more=true;
  ...
  if (someTest()) {
    more = false;
  }
  ...
  if (!more) {
    break;
  }
}

甚至:

do {
  boolean more=true;
  ...
  if (someTest()) {
    more = false;
  }
  ...
  if (!more) {
    break;
  }
} while (true);

我认为在循环之外定义你的条件更清楚。

于 2012-08-02T17:32:38.733 回答
0

KidTempo, in the example you gave, I think that more would be re-initialized each time through the loop. Each time through the loop, the conditional is re-evaluated, so assuming that you are able to define a variable in a conditional, the variable would be re-initialized each time that conditional is re-evaluated. This would also apply to other types of conditionals, so I would say to avoid defining variables in a conditional.

于 2012-08-02T17:36:04.207 回答