Don't worry, this is a common misunderstanding for newcomers, it's not just you. :-) The return
keyword does two things:
Determines what the return value of the function will be, and
Exits the function at that point
Newcomers sometimes think it just does the first, not the second. (And there are languages where the two are in fact done separately, Java just isn't one of them.)
So in your example, the unreachable code is the code after the return false;
, since when the return false;
statement is executed, it exits the function.
Just put it after the other code in that block:
public static boolean zeroCheck(double numberTwo, String operator)
{
if (numberTwo == 0)
{
if (operator.equals("/") || operator.equals("%"))
{
System.out.println("You cannot use a zero to divide or mod.");
}
return false;
}
else // See note #3 below, you don't really need this
{
return true;
}
}
A couple of other notes on the code above:
You don't compare strings in Java with ==
, you use str.equals(otherStr)
. More: How do I compare strings in Java?
Note that I added braces around the inner block (the one attached to if (operator.equals...
). They aren't strictly-speaking necessary, but when you're using braces in the outer block (which you have to), leaving them off the inner block can trip up someone editing the code later.
Since your if
block ends with return false;
, there's no need for the else
; you could just follow the end of the if
block with return true;
It can't be reached if you went into the block, because of course, you exited the function.
The code above returns false
if numberTwo
is 0, even if the operator isn't /
or %
. That's what I think your original code meant to do, but I thought I'd flag it up.
Re #3 above, another option is to remember your return value in a variable:
public static boolean zeroCheck(double numberTwo, String operator)
{
boolean numberTwoIsZero = numberTwo == 0;
if (numberTwoIsZero)
{
if (operator.equals("/") || operator.equals("%"))
{
System.out.println("You cannot use a zero to divide or mod.");
}
}
return numberTwoIsZero;
}