Alettix Alettix - 2 months ago 12
Java Question

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 :)

Answer

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;