在while语句中使用布尔变量

时间:2009-12-07 10:58:22

标签: java boolean

一个新手问题。我有以下Java代码:

 import acm.program.*;
 import java.awt.Color;
 import acm.graphics.*;

 public class ufo extends GraphicsProgram{

    private GRect ufo_ship;
    boolean hasNotLost;
    public void run (){
        setup(); //places ufo_ship to initial position
        hasNotLost = ufo_ship.getY() < 200; //checks if ufo_ship is 
                                        //above the bottom edge of window
        while(hasNotLost){
            move_ufo(); //moves ufo_ship
        }
        showMessage(); //shows that program ended
    }
//remaining methods are here
}

当我运行此代码时,矩形ufoship在到达窗口底部时不会停止。我认为,这是因为它只检查一次ufoship的位置,而不是每次矩形移动时都检查。

有没有办法纠正它而不用简单地写while(ufo_ship.getY() < 200)

4 个答案:

答案 0 :(得分:4)

hasNotLost = ufo_ship.getY() < 200;&lt; - 不将表达式赋值给变量,而是将该表达式计算到的值,因此它当然只计算一次。您可以将其提取到其他方法

boolean hasNotLost(GRect ufo_ship){ return ufo_ship.getY() < 200; }

while(hasNotLost(ufo_ship))
{
  ...
}

ufo可以有自己的类和那个方法,所以你只需要调用while(ufoShip.hasNotLost())

答案 1 :(得分:1)

您可以通过多种方式执行此操作,其中一种方法已在您的问题中突出显示:

while(ufo_ship.getY() < 200)

你也可以这样做:

while(hasNotLost) { move_ufo(); hasNotLost = ufo_ship.getY() < 200; }

或者可以通过引用将hasNotLost传递给move_ufo()并在move_ufo()的末尾进行检查,或者你甚至可以将检查集成到move_ufo中,并从中返回false,所以你可以简单地说:

while(move_ufo()) {}

答案 2 :(得分:1)

while(hasNotLost){
    move_ufo(); //moves ufo_ship
    hasNotLost = ufo_ship.getY() < 200; //checks if ufo_ship is 
                                        //above the bottom edge of window
}

答案 3 :(得分:0)

不,在您的示例代码中,您评估hasNotLost一次并在while语句中使用该(现在为静态)值。它始终是真的(最初评估)

正确的解决方案确实是

while(ufo_ship.getY() < 200) {
  move_ufi();
}

或提取一个类似

的方法
while(ufoStillOnScreen(ufo)) {
  move_ufi();
}

并评估该提取方法中的位置。