OP has a problem in his/her code due to the ^ symbol usage that should be replaced by Math#pow(), good point every one! But he/she's asking what its missing. The answer is very simple: every method must return a value, except for void methods.
If you have
public boolean aBooleanMethod(int x) {
//some fancy and nice code!
return true;
}
The compiler will be happy. But, if you do something like this:
public boolean anotherBooleanMethod(int x) {
if (x < 2) {
return true;
}
}
The compiler will throw an exception:
This method must return a result of type boolean.
Why is this? Because at the end of the method, the compiler find a path that could not return a value, so instead of make your program crash or return an unexpected result (like false when there is no return associated), the Java compiler will throw the exception.
How to solve it? Easy: don't forget to return a value on every path in your method.
Ways to solve the problem in the last piece of code:
Adding a default return at the end of the method. This is a common approach used by almost all programmers.
public boolean anotherBooleanMethod(int x) {
if (x < 2) {
return true;
}
//if the method has never returned true, then it must return false...
return false;
}
For boolean results, you can return a condition:
public boolean anotherBooleanMethod(int x) {
//your method always return a value, no compiler problems
//the value depends if x is less than 2 (true) or 2 or more (false)
return (x < 2);
}
About the exception of the void methods, this doesn't mean that a void method can't use the return keyword, just means that it must return "nothing". To post a sample:
public void theVoidMethod(int x) {
System.out.println("Welcome to theVoidMethod!");
if (x < 2) {
//return nothing! End of the method
return;
}
System.out.println("You've reached the bottom of theVoidMethod!");
//here, the Java compiler will add a return sentence for you, no need to code it
//return
}
If you test this method using 1 and 2 as parameters you will get different results:
theVoidMethod(1):
Welcome to theVoidMethod!
theVoidMethod(2):
Welcome to theVoidMethod!
You've reached the bottom of theVoidMethod!
Now, to solve another problems in your code, you should use the Math#pow method instead of ^ symbol, but that's heavily explained in the other answers.
ifcondition is not satisfied so, in else part you need to return else. For these type of coding its better to useflags.