Reputation: 107
public boolean isOdd (int value) {
if ((value % 2)== 0){
return false;
} else if ((value % 2) > 0){
return true;
}
}
I get an error saying: private boolean isOdd(int value) throws Exception{ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This method must return a result of type boolean
I tried doing:
public boolean isOdd (int value) {
boolean isOdd = ((value % 2) > 0);
return true;
}
public boolean isEven (int value) {
boolean isEven = ((value % 2) > 0);
return true;
}
and it only returns true as an output.
I have no clue what I'm doing wrong here!
Upvotes: 4
Views: 49583
Reputation: 1
You can also do:
public boolean isOdd (int value) {
if ((value % 2) == 0)
return false;
return true;
}
Upvotes: 0
Reputation: 7846
The compile error would go away if you added an else
statement, i.e.
if ((value % 2)== 0) {
return false;
} else if ((value % 2) > 0){
return true;
} else {
return ??; // default value
}
Upvotes: 2
Reputation: 3296
You need an else or at least another return. If neither of your if statements match then nothing will be returned and that is not allowed.
public boolean isOdd (int value) {
if ((value % 2)== 0){
return false; }
else if ((value % 2) > 0){
return true; }
return true;
}
You could replace the method with the below method:
public boolean isOdd (int value) {
return (value % 2) != 0; }
Upvotes: 2
Reputation: 1334
Just do
public boolean isOdd(int value) {
return (value % 2) != 0;
}
Upvotes: 2
Reputation: 1373
Your first code snippet is causing an error because you have not catered for the else
case. You do not need an else if
here as you want the second condition to execute in all cases where the if statement is not satisfied. Try changing it to:
public boolean isOdd (int value) {
if ((value % 2)== 0){
return false;
}
else { return true; }
}
or more simply:
public boolean isOdd (int value) {
return ((value % 2) != 0);
}
Upvotes: 10
Reputation: 60711
What if ((value % 2) < 0)
? You aren't catering for that possibility, and there is no return path if that happens.
Upvotes: 1
Reputation: 13986
public boolean isEven (int value) {
return value%2==0;
}
public boolean isOdd (int value) {
return value%2!=0;
}
Upvotes: 0
Reputation:
You need to add a default return value in the first snippet, aka one that is not inside any if.
Upvotes: 5