Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method not returning value when encountering "return" in an "if"

Tags:

java

methods

My problem is that this method "isLargest" doesn't end when it meets "return true;". Even if the condition in "else if" is true, it seems to just skip it and always returns "false". I even printed a word "test" to prove that. When I use the method, it says "test" and returns false.

I tried to put this "return false" inside an else or another else if, but then is says that "This method must return boolean type" and proposes me to add return statement. How do I deal with that?

public boolean isLargest(Node tmp, Node parent){
    if(tmp.value > parent.value){
        parent = parent.right;
        tmp.isLargest(tmp, parent);
    }
    else if(parent.value == tmp.value){
        System.out.println("test");
        return true;
    }       
    return false;
like image 459
Michael Xaxaxa Avatar asked Dec 30 '25 01:12

Michael Xaxaxa


1 Answers

When you have a recursive call, you need to return the value of the recursive call.

public boolean isLargest(Node tmp, Node parent){
if(tmp.value > parent.value){
    parent = parent.right;
    return tmp.isLargest(tmp, parent);
}
else if(parent.value == tmp.value){
    System.out.println("test");
    return true;
}       
return false;
like image 163
Emerson Cod Avatar answered Dec 31 '25 19:12

Emerson Cod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!