Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return boolean in Java?

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!

like image 288
Kimmm Avatar asked Nov 29 '22 01:11

Kimmm


1 Answers

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);
}
like image 146
Joe Elleson Avatar answered Dec 04 '22 01:12

Joe Elleson