想請教為何最底下那段 if (p1isRight || p2isRight || p3isRight) {
程式碼會錯誤,它宣告在starGame()方法裡,if這段判斷式也是在starGame()裡照理說boolean的變數還活著,但卻會出現Unreachable code的錯誤...
我如果把while區塊裡的程式碼移除,if那段就不會有錯誤?....為什麼..
剛在學...請大家指點指點了..
package guess.game;
public class GuessGame {
Player p1, p2, p3;
public void starGame() {
// 建構三個Player物件
p1 = new Player();
p2 = new Player();
p3 = new Player();
// 儲存猜測的數字
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
// 用來確定是否猜測正確
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
int targetNumber = (int) (Math.random() * 10);
System.out.println("I'am thinking of a number between 0 and 9 ...");
while (true) {
System.out.println("Number to guess is " + targetNumber);
// 呼叫Player猜測號碼
p1.guess();
p2.guess();
p3.guess();
//
guessp1 = p1.number;
System.out.println("Player one guessed " + guessp1);
guessp2 = p2.number;
System.out.println("Player one guessed " + guessp2);
guessp3 = p3.number;
System.out.println("Player one guessed " + guessp3);
if (guessp1 == targetNumber)
p1isRight = true;
if (guessp2 == targetNumber)
p2isRight = true;
if (guessp3 == targetNumber)
p3isRight = true;
}
if (p1isRight || p2isRight || p3isRight) { //為什麼此段程式碼會錯誤
System.out.println("Game is over.!");
}
}
}
因為 25 行的 while(true) 是無窮迴圈。從 25 到 48 行沒有任何 break 指令。也就是一進去就跳不出來了,當然底下的程式碼是 Unreachable code (永遠不會執行的程式段)。