NPN328
NPN328

Reputation: 1942

Method is returning int type, but I keep getting "this method must return a result of type int" error

This is the code:

private int getUpSite(int i, int j){
    if (i - 1 >= 1){
        if (grid[i - 2][j] != 0){
            return xyTo1D(i - 1, j);
        }
    }
    else{
        return -1;
    }
}

Depending on the values of i and j, the method returns -1 or another integer built by the xyTo1D method. The problem is that the compiler keeps complaining: "this method must return a result of type int".

What is wrong with the code? How do I fix this?

Upvotes: 2

Views: 312

Answers (3)

Rajj
Rajj

Reputation: 101

private int getUpSite(int i, int j){   
    int returnValue=-1;   
    if (i - 1 >= 1 && grid[i - 2][j] != 0){
       returnValue = xyTo1D(i - 1, j);
    }
    return returnValue;
}

Upvotes: 0

kosa
kosa

Reputation: 66637

What happens if control doesn't enter second level if?

if (grid[i - 2][j] != 0)

There is no return statement, isn't it?

You need to have a return statement for all possible paths.

How do I fix this?

One possible way:

Add return statement for first level if too. Example

if (i - 1 >= 1){
        if (grid[i - 2][j] != 0){
            return xyTo1D(i - 1, j);
        }
       return -1; //OR whatever int you would like to return
    }

Upvotes: 6

Crickcoder
Crickcoder

Reputation: 2155

private int getUpSite(int i, int j){
int returnVal = -1;
    if (i - 1 >= 1){
        if (grid[i - 2][j] != 0){
            returnVal = xyTo1D(i - 1, j);
        }
    }
return returnVal;
}

Upvotes: 1

Related Questions