Java 在while语句中使用布尔变量

Java 在while语句中使用布尔变量,java,boolean,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

一个新手问题。我有以下一段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
}
导入acm.program.*;
导入java.awt.Color;
导入acm图形。*;
公共类ufo扩展图形程序{
私人GRect ufo_船;
布尔值没有丢失;
公开作废运行(){
setup();//将ufo_飞船放置到初始位置
hasNotLost=ufo\u ship.getY()<200;//检查ufo\u ship是否正确
//在窗户的底边上方
虽然(没有迷失){
移动不明飞行物();//移动不明飞行物
}
showMessage();//显示程序已结束
}
//剩下的方法在这里
}
当我运行此代码时,矩形ufoship在到达窗口底部时不会停止。我假设,这是因为它只检查一次ufoship的位置,而不是每次矩形移动


有没有什么方法可以在(ufo_ship.getY()<200)时不简单地编写
来纠正它?

hasNotLost=ufo_ship.getY()<200
hasNotLost=ufo_ship.getY()<200有很多方法可以做到这一点,您在问题中强调了其中一种方法:

while(ufo_ship.getY() < 200)

有很多方法可以做到这一点,您在问题中强调了其中一种方法:

while(ufo_ship.getY() < 200)
while(hasNotLost){
移动不明飞行物();//移动不明飞行物
hasNotLost=ufo\u ship.getY()<200;//检查ufo\u ship是否正确
//在窗户的底边上方
}
while(hasNotLost){
移动不明飞行物();//移动不明飞行物
hasNotLost=ufo\u ship.getY()<200;//检查ufo\u ship是否正确
//在窗户的底边上方
}

否,在示例代码中,计算hasNotLost一次,并在while语句中使用该值(现在为静态值)。它总是正确的(正如最初评估的那样)

正确的解决办法确实是

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

然后计算提取方法中的位置。

否,在示例代码中,计算hasNotLost一次,并在while语句中使用该值(现在是静态的)。它总是正确的(正如最初评估的那样)

正确的解决办法确实是

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

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

+1用于直觉提问者可能正在将表达式分配给变量,这正是我认为他们可能正在做的。将条件分解为函数可消除重复,并与变量具有相同的用途,这正说明了条件的含义。谢谢你的回答。创建一个新方法hasNotLost是最好的解决方案,因为我想添加更多的条件来结束程序。+1用于直觉提问者可能正在将表达式分配给变量,这正是我认为他们可能正在做的。将条件分解为一个函数可以消除重复,并与变量的作用相同,即确切说明条件的含义。谢谢回答。创建一个新方法hasNotLost是最好的解决方案,因为我想添加更多的条件来结束程序。
while(hasNotLost){
    move_ufo(); //moves ufo_ship
    hasNotLost = ufo_ship.getY() < 200; //checks if ufo_ship is 
                                        //above the bottom edge of window
}
while(ufo_ship.getY() < 200) {
  move_ufi();
}
while(ufoStillOnScreen(ufo)) {
  move_ufi();
}