-1

anyone could please explain?

class Main{
    
    static String CountAndSay(int n)
    {
        if (n==1){
        return "1";
        }
        if(n==2)
        {
        return "11";
        }
    }
    public static void main (String[] args) 
    {
        System.out.println(CountAndSay(1));
      
    }
}

Ans:- Main.java:12: error: missing return statement } ^

BUT when I write the return statement after if statement it's working.

class Main{
    
    static String CountAndSay(int n)
    {
        if (n==1){
        return "1";
        }
        if(n==2)
        {
        return "11";
        }
        return "0";
    }
    public static void main (String[] args) 
    {
        System.out.println(CountAndSay(1));
      
    }
}

ans:- 1

SSK
  • 3,444
  • 6
  • 32
  • 59
  • 2
    A method with non-void return type needs to return something. What is there to explain. – Amongalen Feb 25 '21 at 13:49
  • 4
    Does this answer your question? ["Missing return statement" within if / for / while](https://stackoverflow.com/questions/23058029/missing-return-statement-within-if-for-while) –  Feb 25 '21 at 13:50
  • Just think about it. In your first method, what is returned when `n` is neither 1 or 2? – QBrute Feb 25 '21 at 14:04
  • just think what happens if value of n is say 3, the function cannot return anything. so make sure to have return statements in all conditional branches. – Harsh Feb 25 '21 at 14:14

2 Answers2

0

the first scenario doesn't have a return statement for conditions beside the two if statements. What if it goes out of the two conditions? like you pass in 3 inside your method like this CountAndSay(3)? It doesn't know what to return. so if you have two if returns without else condition you need a default return statement. or an other way of putting your statement will be:

 static String CountAndSay(int n)
    {
        if (n==1){
           return "1";
        }else if(n==2)
        {
           return "11";
        }else{
           return "";//anything you think as a default.
        }
    }
Kidus Tekeste
  • 651
  • 2
  • 10
  • 28
0

You always need a return statement, if none of the if's are targeted. The one down below works, because 'return 0' is called, even if no other return is called. If in the upper one the parameter is for example 3, it wouldn't call any if statements, so there is no return value, hence an error.