2014-10-28 206 views
-3

我正在使用while循環,它不會在它應該時終止。如果它工作正常,那麼當randno== highbound== lowbound時它會終止。while循環不會終止?

代碼循環的:

do { 
    do { 
     randno = (int) (Math.round((Math.random()*(4)) + 0.5)-1); 
     direction = getDirection(randno,heading);  
    } while (robot.look(direction)==IRobot.WALL); 
    System.out.println(randno); 
    System.out.println(highbound); 
    System.out.println(lowbound); 
    System.out.println("---------------"); 
} while (randno!=lowbound | randno!=highbound); 

的輸出是任一3 3 2 ------,或2 3 2 ------,因此該循環應該結束。第一個循環正常結束(我嵌入它們試圖讓它工作...)。出了什麼問題?

+0

它是'while'循環,而不是'until'循環,因此它必須與低位*和*高位不同,以繼續循環,而不是*或*。 – 2014-10-28 11:14:55

回答

5

randno!=lowbound | randno!=highbound總是爲真,因爲randno不能等於兩個lowboundhighbound(假設它們不相等)。

因此,循環永遠不會終止。

如果您想終止時randno比這兩個界限不同,你的條件更改爲:

while (randno==lowbound || randno==highbound) 

如果您想終止時randno是一樣的邊界之一,改變你的條件:

while (randno!=lowbound && randno!=highbound) 

編輯:根據你的問題,你想第二個選項。

+0

嘿,非常感謝你!我知道這可能是一個愚蠢的問題,但我真的一直在盯着它幾個小時...... – LozzaManiac 2014-10-28 12:09:14