user8203210
user8203210

Reputation:

function requiring more than one return statements

I am posting here two functions. In the findPrime(int m, int i, int n) I have one outer if and outer else block from both the block I am getting return so it can be considered that the function is returning something I put same structure in endOther(String a, String b) i.e. there are two main if-else blocks both are returning value as per function's return type so we can say that function is returning something but the endOther(String a, String b) function is throwing compile time error saying that put return statement while first function is not throwing such error. I am not understanding this issue please help me. Type both the functions in eclipse and check

1.

static boolean findPrime(int m, int i, int n){
    if(n == 0 || n == 1)
        return false;
    else {
        if(i <= m) {
            if(n%i == 0)
                //if(m%i == 0)
                return false;
            else {
                i++;
                //return findPrime(m,i);
                return findPrime(m,i,n);
            }

        }
        else {
            return true;
        }
    }
}

2.

public boolean endOther(String a, String b) {
    if(a.length()==b.length()) {
        if(a.equals(b))
            return true;
        else
            return false;
    }
    else {
        if(a.length()>b.length()) {
            if(a.substring(a.length()-b.length(),b.length()).equals(b))
                return true;
        }
        else { 
            if(b.substring(b.length()-a.length(),a.length()).equals(a))
                return true;
            else
                return false;
        }
    }
}

Upvotes: 0

Views: 32

Answers (1)

Jens
Jens

Reputation: 9416

Your endOther function must return a value on all possible execution paths. In case a.length() > b.length() the return may not be executed based on the condition of the inner if.

public boolean endOther(String a, String b) {
    if(a.length()==b.length()) {
        if(a.equals(b))
            return true;
        else
            return false;
    }
    else {
        if(a.length()>b.length()) {
            // IF THIS FAILS THERE IS NO RETURN!
            if(a.substring(a.length()-b.length(),b.length()).equals(b))
                return true;
        }
        else { 
            if(b.substring(b.length()-a.length(),a.length()).equals(a))
                return true;
            else
                return false;
        }
    }
}

As a general note, you could use some of the methods in String to improve your code, e.g. String.endsWith instead of the substring operation. This would be more readable. a and b being identical is a special case of String.endsWith, so the following should be equivalent:

public boolean endOther(String a, String b) {
    return a.endsWith(b) || b.endsWith(a);
}

Upvotes: 2

Related Questions