为什么这个方法会返回错误:Error: Unreachable code 谢谢!
public static boolean zeroCheck(double numberTwo, String operator) {
if (numberTwo == 0) {
return false;
if(operator == "/" || operator == "%")
System.out.println("You cannot use a zero to divide or mod.");
} else return true;
}
}
错误:
File: C:\JAVA\LABS\LabSix.java [line: 228]
Error: Unreachable code
在继续执行从未到达的其余代码之前,您返回
一个值。当您使用 return
语句时,它会自动结束代码并根据您的情况返回 boolean
。
只需将 return
语句放在 block 的末尾即可。
public static boolean zeroCheck(double numberTwo, String operator) {
if (numberTwo == 0) {
if (operator == "/" || operator == "%") {
System.out.println("You cannot use a zero to divide or mod.");
}
return false;
} else return true
}
顺便说一句,如果你想比较String
,请使用equals(..)
方法,因为String
不是原始类型类型如 int
或 double
等。通常,在比较所有对象时使用 equals(..)
。
if (operator.equals("/") || operator.equals("%"))