Codewars - Kata problems

Error message:
./src/main/java/ error: missing return statement
1 error

My code:

public class Counter {
  public int countSheeps(Boolean[] arrayOfSheeps) {
    for(int i = 0; i < arrayOfSheeps.length; i++){
      int numSheep = 0;
      if(arrayOfSheeps[i] == true){
        numSheep += 1;
        return numSheep;

I have gotten this error on 2 different katas or problems and I can’t understand why. Any ideas?


The error message is descriptive, implying that a return statement is not being reached in the method. Consider if conditional branching affects this!

For future posts, it’s easier for people to help if the code is formatted ([How to] Format code in posts) :slight_smile:


What do you mean by a return statement not being reached in the method and what is conditional branching?

Thank you very much for your reply though!

Conditional branching is anything that asks: if this, else that etc.

Basically, the compiler is not going to be as smart as one might assume in knowing you will for sure reach anything inside a conditional. So in that case, does the compiler think you have a return statement that always runs in your method?



This catches a lot of people out. :+1:

I swear this used to be in the Java docs, but every time I try and find it these days I can’t find it…


Yea same thing happened to me! I thought my mind was playing tricks on me…

Again thank you very much for your response. I understand what you mean by the conditional branching now! I don’t think the compiler would think that a return statement would always run, though I’m not sure exactly what that means. First of all, I took the return statement right out (it was just return an integer from counting the number of true statements in an array) and I got the same error. So I just let the counter count every time the loop got a true statement with an if statement. Someone said I might be looping from the wrong spot, but I started at 0((int i = 0;), it goes until the length of the array has been reached (i < countSheeps.length;), and counts up (i++;). This seems to be the most basic looping problem, in all I’ve learned so far this code should work.

For the sake of argument what happens when you replace return 1 at the end of the method?

Java has a requirement that your method must have a return statement that can always be reached, regardless of the procedural flow of your program.

If your method has a return, but it’s inside an if ... else structure, the compiler does not have the appropriate run-time information to determine whether that return statement can be reached. It therefore assumes that it can’t.

Generally it’s possible to refactor the method to avoid the problem; if not, a cheap (and probably not recommended) workaround would be to put a return on the last line of the method. :slight_smile:

1 Like