2015-12-01 80 views
2

這是一個來自我的代碼的方法,當我嘗試編譯它時,它向我拋出'無法訪問的語句'錯誤。編譯器給我一個'無法訪問的語句'錯誤

public static boolean whoareyou(String player) 
{ 
    boolean playerwhat; 
    if (player.equalsIgnoreCase("Player 1")) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
    return playerwhat; 
} 

確切的錯誤是:

java:82: error: unreachable statement 
       return playerwhat; 
       ^

然後我嘗試使用這個布爾我返回下面的代碼:

public static int questions(int diceroll, int[] scorep1) 
{ 
String wanttocont = " "; 
boolean playerwhat; 
for (int i = 0; i <= 6; i++) 
{ 
    while (!wanttocont.equalsIgnoreCase("No")) 
    { 
    wanttocont = input("Do you wish to continue?"); 
    // boolean playerwhat; wasn't sure to declare here or outside loop 
    if (diceroll == 1) 
    { 
     String textinput = input("What's 9+10?"); 
     int ans1 = Integer.parseInt(textinput); 
     output("That's certainly an interesting answer."); 
     if (ans1 == 19) 
     { 
      if (playerwhat = true) 
      { 
      output("Fantastic answer player 1, that's correct!"); 
      diceroll = dicethrow(diceroll); 
      scorep1[0] = scorep1[0] + diceroll; 
      output("Move forward " + diceroll + " squares. You are on square " + scorep1[0]); 
      } 
      else if (playerwhat = false) 
      { 
      output("Fantastic answer player 2, that's correct!"); 
      diceroll = dicethrow(diceroll); 
      scorep1[1] = scorep1[1] + diceroll; 
      output("Move forward " + diceroll + " squares. You are on square " + scorep1[1]); 
      } 
    } // END if diceroll is 1 
    } // END while wanttocont 
} // END for loop 
} // END questions 

我不知道,如果上面的代碼與這個問題有關,但我只是想顯示我正試圖做的事情是拋出錯誤的布爾值。謝謝。

回答

2

return playerwhat;永遠無法到達,因爲ifelse子句將返回truefalse。因此你應該刪除這個語句。 playerwhat變量不是必需的。

順便說一句,你的方法可以用一個襯墊的方法來代替:

public static boolean whoareyou(String player) 
{ 
    return player.equalsIgnoreCase("Player 1"); 
} 

我將這個方法重新命名爲更具描述性,如isFirstPlayer

編輯:

你永遠不會調用whoareyou是你questions方法。你應該把它叫做:

更換

if (playerwhat = true) // this is assigning true to that variable, not comparing it to true 

if (whoareyou(whateverStringContainsTheCurrentPlayer)) { 
    .. 
} else { 
    ... 
} 
+0

你是說在'whoareyou'方法的結尾處​​刪除'return playerwhat'?如果我這樣做,那麼就沒有任何東西被傳遞給'question'方法,因爲當我說我是玩家2之後回答了一個問題時,它仍然說'真棒回答玩家1,這是正確的!說'玩家2'。 – Overclock

+0

@Overclock請參閱編輯。這與你的「問題」方法有一個不同的問題。 – Eran

+0

非常感謝!我調整了一下你說的一些話,但它確實有效。 – Overclock

2

只需更新代碼這樣

public static boolean whoareyou(String player) 
{ 
    boolean playerwhat; 
    if (player.equalsIgnoreCase("Player 1")) 
    { 
     playerwhat = true; 
    } 
    else 
    { 
     playerwhat = false; 
    } 
    return playerwhat; 
} 
+0

我更喜歡'if(「Player 1」.equalsIgnoreCase(player))' – SpringLearner

+0

@SpringLearner同意我們也可以這樣做,但是我只是按照他原來的代碼發佈 – swiftBoy

2

試試這個:

public static boolean whoareyou(String player) 
{ 
    return player.equalsIgnoreCase("Player 1"); 
} 

你有問題,因爲:

return player what; 

從未達到。您可以通過「if」或通過「else」部分退出您的功能。

相關問題