Reputation: 431
Here is my method:
public int power(int x, int n) {
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
}
}
Compiler is displaying this message:
Method breakpoint:Tester [entry] - power(int, int) - This method must return a result of type int" message.
Can't seem to figure out what the issue is.
I know it's bad practice, but I've been instructed not to store values in a local variable and return it at the end.
What am I missing here?
Upvotes: 2
Views: 1175
Reputation: 424983
If n
is other than one of your cases, nothing will be returned - that's what the compiler is complaining about.
Since your implementation only caters for n being 2, 3 and 4, the most appropriate thing to do is throw an exception:
public int power(int x, int n) {
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
}
throw new IllegalArgumentException("Power must be 2, 3 or 4. Unsupported power: " + n);
}
The compiler will then be satisfied that all code paths either return something or an exception is thrown.
Upvotes: 4
Reputation: 17132
Add a default
case to your switch
:
case ...:
return ...
...
default:
return 0; // return some default value in case no other case was executed
Note that the default
case must return an Integer, otherwise the error shall persist.
Upvotes: 1
Reputation: 60094
You must add default case or return after switch (because Java didn't what retuns if n isn't 2, 3 or 4):
public int power(int x,int n){
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
}
return 0;
}
or
public int power(int x,int n){
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
default: return 0;
}
}
Upvotes: 0
Reputation:
public int power(int x,int n){
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
}
return 0;
}
I guess it's because you don't have main return state. switch case can be bypass if n doesnt initialized correctly but compiler need return value if you define power as a int power () ... If it return 0 you will know n isn't initialized well
Upvotes: 1