Self made class, not returning when it a loop?

Ship findShip(int[] coordinates){
  for (int i = 0; i < ships.size();i++){
    Ship ship = ships.get(i);
    int shipX = ship.x;
    int shipY = ship.y;
    for (int tile = 0; tile < ship.size; tile++){
      if (ship.rotated){
        if (shipY == coordinates[1] && shipX + tile == coordinates[0]){
          return ship;
        }
      }
      else{
        if(shipY + tile == coordinates[1] && shipX == coordinates[0]){
          return ship;
        }
      }
    }
  }
}

The console returns that the return type must be a Ship, I have been playing with the scope for days and it is killing me
This method must return a result of type UltimateBattleshipV2.Ship.

1 Like

You must return a ship also outside any if

At the very end for example

or return null there

1 Like

This would be a problem even if the for loop guaranteed a match somehow: if ships.size==0, then the for loop will never run, and so findShip will never return anything.

findShip must return something.

So the last line needs to return either null or a Ship object (like a special not-a-Ship or default ship. Probably just return null, then handle that when you call findShip – check if what it returned was nothing.