Search code examples
javareturnstatements

Missing return statement when trying to return a boolean value


I keep getting an error in java and I don't know why "missing return statement". What I'm trying to do is create a method with two parameters (String and char) check if the char appears in the string and return a boolean value based on the comparison. Here's what I have so far:

  public static boolean compare(String h, char x){

int counter = 0;
for(int i = 0; i < h.length(); i++){
  counter++;
  if(h.charAt(i) == 'o'){
    return true;
  }
  else
    return false;
}

  }

Again, the error in the console is "missing return statement". Please be aware that I'm not an expert in Java and probably I have more errors in my code, my apologize in advance for that.

edit: Don't look at the indentation, I just copy and paste the code here. edit 2: "h" is "Hello world" in my code.


Solution

  • You should assign the boolean result to a variable instead of returning it in the loop. Add the return statement after the for loop, this should fix your issue. HTH

     public static boolean compare(String h, char x){
    
           int counter = 0;
           boolean flag = false;
    
           for(int i = 0; i < h.length(); i++){
             counter++;
             if(h.charAt(i) == 'o'){
                 flag = true;
             }
             else
                 flag = false;
           }
            return flag;
    }