2009-12-07 137 views
0

新手問題。我有下面的一段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)

回答

4

hasNotLost = ufo_ship.getY() < 200; < - 不將表達式賦值給變量,而是將表達式計算到的值,所以它當然只計算一次。你可以把它解壓到其他方法

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

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

UFO可能有自己的類和方法,所以你只需調用而(ufoShip.hasNotLost())

+0

+1對於直覺來說,提問者可能會將表達式分配給變量,這正是我認爲他們可能會做的事情。 – 2009-12-07 11:04:29

+0

將條件分解爲一個函數可以消除重複,並達到與變量相同的目的,該變量正確地說明條件的含義。 – 2009-12-07 11:08:15

+1

感謝您的回答。 創建一個新方法hasNotLost是最好的解決方案,因爲我想添加更多條件來結束程序。 – 2009-12-07 11:12:59

1

有一些你可以做到這一點的方式,其中之一,你在你的問題已經凸顯:

while(ufo_ship.getY() < 200) 

你也可以這樣做:

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

或者可以參照到move_ufo(通過hasNotLost)和move_ufo年底做檢查(),或者你甚至可以將檢查融入move_ufo,並返回從中假的,所以你可以簡單地說:

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

不,在您的示例代碼中,您評估hasNotLost一次,並在while語句中使用該值(現在是static)。這將永遠是真實的(最初評估)

正確的解決方案確實是

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

或提取方法的做類似

while(ufoStillOnScreen(ufo)) { 
    move_ufi(); 
} 

和評估在提取方法的位置。