新手問題。我有下面的一段Java代碼:while語句中使用布爾變量
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)
?
+1對於直覺來說,提問者可能會將表達式分配給變量,這正是我認爲他們可能會做的事情。 – 2009-12-07 11:04:29
將條件分解爲一個函數可以消除重複,並達到與變量相同的目的,該變量正確地說明條件的含義。 – 2009-12-07 11:08:15
感謝您的回答。 創建一個新方法hasNotLost是最好的解決方案,因爲我想添加更多條件來結束程序。 – 2009-12-07 11:12:59