A newbie question. I have the following piece of Java code:
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
}
When I run this code, the rectangle ufoship does not stop when it reaches the bottom of the window. I assume, that it’s because it checks position of the ufoship only once, and not every time the rectangle moves.
Is there any way to correct it without writing simply while(ufo_ship.getY() < 200)?
hasNotLost = ufo_ship.getY() < 200;<- Does not assign expression to the variable, but the value to which that expression is being computed, so it of course is computed only once. You can extract it to other methodufo could have own class and that method so you would just call while(ufoShip.hasNotLost())