0

Here is a snippet of my code:

public static int dc (String s,int k, int c){
  String s1, s2;
  int m, n;
  if (check(s, k) != -1) {
    int p = check(s, k);
    c++;
    s1 = s.substring(0, p) + s.substring(p + 1);
    s2 = s.substring(0, p + 1) + s.substring(p + 2);
    if ((check(s1, k) == -1) || (check(s2, k) == -1)) {
      return c;
    } else {
      m = dc(s1, k, c);
      n = dc(s2, k, c);
      if (m > n) {
        return n;
      } else {
        return m;
      }
    }
  }
}

So the error says that there is a missing return statement (not sure which scenario have I missed). But when I add a return statement at the end, it shows that return statement unreachable. I've found an helpful answer here: Unreachable return statement still throws error and I have tried putting it in a try catch block but it still asks for a return statement. Even though the compiler knows that anything I write in the end is redundant, why is it still showing an error?

Community
  • 1
  • 1
Rohinb97
  • 121
  • 5
  • This method isn't missing a `return` statement on any branch. Perhaps the problem is with your `check` method? Could you include its code? – Mureinik May 29 '16 at 07:11
  • 2
    You must have a return statement at the end, in case the first if condition is false. Your life would be easier if you use proper indentation. – Eran May 29 '16 at 07:11
  • The code goes into this method only if check isn't -1. Should I post the entire code? – Rohinb97 May 29 '16 at 07:18
  • You've said the method returns an int, but what happens if that first if fails? You can only get away with no return statement in this kind of situation if the signature for the method returns void. – Carl Whalley May 29 '16 at 07:19
  • I just added that if statement to explain it to my friend. Removing it makes it work. This was stupid of me. Thanks everyone. – Rohinb97 May 29 '16 at 07:24

3 Answers3

1

The first if Block doesn't have else...

if(check(s,k)!=-1){

...... }

Md Faraz
  • 307
  • 1
  • 4
  • 16
1

If your first check check(s, k) returns -1 then you don't return anything

Nikem
  • 5,716
  • 3
  • 32
  • 59
0

public static int dc(String s, int k,int c){ String s1,s2; int m,n; if(check(s,k)!=-1) { int p=check(s,k); c++; s1=s.substring(0,p)+s.substring(p+1); s2=s.substring(0,p+1)+s.substring(p+2); if((check(s1,k)==-1)||(check(s2,k)==-1)){ return c; } else{ m=dc(s1,k,c); n=dc(s2,k,c); if(m>n){ return n; } else{ return m; } } } // MISSING RETURN BELOW return n; }

I suggest using an IDE like eclipse, it'll help you spot these things. It literally added the statement for me.

TheFooBarWay
  • 594
  • 1
  • 7
  • 17
  • Well I do use Eclipse but I was directly coding it on codechef so I got lazy and didn't add indentations – Rohinb97 May 29 '16 at 07:25