Jhonny
Jhonny

Reputation: 185

Missing return statement java

I have a 8x8 grid of cells, which can be either true (1) or false (0). I am trying to write a method in java which counts the number of true cells neighbouring a specified cell in column "col" and row "row". "world" is a variable describing the initial states of each cell (every bit represents a cell). getCell is a method which returns the boolean value of a cell specified by its parameters. I have tested the getCell method and it has passed all my tests, so I believe it works as intended. My code looks like this:

public static int countNeighbours(long world, int col, int row){
    int numNeighbours = 0;`

    if(getCell(world,col-1,row-1))
        numNeighbours++;
    if(getCell(world,col,row-1))
        numNeighbours++;
    if(getCell(world,col+1,row+1))
        numNeighbours++;
    if(getCell(world,col-1,row))
        numNeighbours++;
    if(getCell(world,col+1,row))
        numNeighbours++;
    if(getCell(world,col-1,row+1))
        numNeighbours++;
    if(getCell(world,col,row+1))
        numNeighbours++;
    if(getCell(world,col+1,row+1))

    return numNeighbours;
}

Esentially, it should work like this:

  1. The initial number of true neighbours is 0

  2. It then tests all surrounding cells, if any of them are true it increments numNeighbours by 1

  3. At the end it returns the final numNeighbours

However, when I try to comply it I get an error message saying "error missing return statement". Why is it so? As far as I see, there is very clearly a return statement in the end. Could anybody please provide me som advice?

Many Thanks :)

Upvotes: 1

Views: 183

Answers (2)

Andrew
Andrew

Reputation: 49606

Your return statement relates to the last if statement:

if(getCell(world,col+1,row+1)) return numNeighbours;

You'd better either change a body of the last if statement [1] or put another return in the end [2]:

// [1]
if(getCell(world,col+1,row+1)) {
    // a body
}
return numNeighbours;
...
// [2]
if(getCell(world,col+1,row+1)) {
    return numNeighbours;
}
return numNeighbours;

Note that I used a pair of curly braces to emphasise the statement body (it will prevent further mistakes), I'd recommend you doing so.

Upvotes: 1

Eran
Eran

Reputation: 393771

You forgot to increment numNeighbours in the last condition. Therefore, your return statement was only executed if the last condition was true :

if(getCell(world,col+1,row+1))

return numNeighbours;

Change it to :

if(getCell(world,col+1,row+1))
    numNeighbours++; // added 

return numNeighbours;

Upvotes: 3

Related Questions