Reputation: 73
This is a method from my code and it's throwing me an 'unreachable statement' error when I attempt to compile it.
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
return true;
}
else
{
return false;
}
return playerwhat;
}
The exact error is:
java:82: error: unreachable statement
return playerwhat;
^
I then attempt to use this boolean I return in the following code:
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
I'm not sure if the above code is relevant to the question but I just wanted to show what I'm attempting to do with the boolean that is throwing me the error. Thank you.
Upvotes: 2
Views: 56
Reputation: 394146
return playerwhat;
can never be reached, since either the if
or else
clause will return true
or false
. Therefore you should remove this statement. The playerwhat
variable is not required.
BTW, your method can be replaced with a one liner method :
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
I would rename this method to something more descriptive, such as isFirstPlayer
.
EDIT :
You never call whoareyou
is your questions
method. You should call it :
Replace
if (playerwhat = true) // this is assigning true to that variable, not comparing it to true
with
if (whoareyou(whateverStringContainsTheCurrentPlayer)) {
..
} else {
...
}
Upvotes: 2
Reputation: 2916
Try this:
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
You have the issue, because:
return player what;
is never reached. You exit the your function either through the "if"- or through the "else"-part.
Upvotes: 2
Reputation: 35783
Just update your code this way
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
playerwhat = true;
}
else
{
playerwhat = false;
}
return playerwhat;
}
Upvotes: 2