Java error "missing return statment"

I can't seem to find where the error is. All the possible values of n are covered. If I add a simple return value outside of the if-statment, it will work, but I don't see why that should be the case. Also, I'd like to add a print "i" statement into main, but whenever I do something like:

if (something)< int i; i++; do something 
I try to add a System.out.println(i) and it gives me an error about a static variable. 31.2k 15 15 gold badges 57 57 silver badges 81 81 bronze badges asked Sep 6, 2016 at 3:06 601 3 3 gold badges 13 13 silver badges 26 26 bronze badges You're missing a closing bracket. Commented Sep 6, 2016 at 3:07 What are you returning if n is 0? Commented Sep 6, 2016 at 3:07 @Andreas The code won't even get that far. Commented Sep 6, 2016 at 3:08

@TimBiegeleisen I can't find an open bracket. Maybe it's because I'm just using a simple text editor, but everything looks closed to me.

Commented Sep 6, 2016 at 3:10

@TimBiegeleisen Don't understand you comment. "Missing brace" and "missing return" are both compiler errors, so code don't go anywhere in either case.

Commented Sep 6, 2016 at 3:10

3 Answers 3

Your code makes no sense, as posted. You have an if/else statement with three branches. The first branch is executed if n%2 is 0. The second branch is executed if n%2 is not zero. Since that covers all the possibilities, when is the third branch supposed to be executed?

Because this doesn't make sense (and because I've seen this coding problem before), I suspect that you meant the third branch to be executed if the first if is false, i.e. if n 1) . To fix this, you need another curly brace:

public static int F(int n) < if (n >1) < // ***** Opening brace 1 if (n%2 == 0)< n = n/2; System.out.println(n); return F(n); >else if(n%2 != 0) < // ***** Opening brace 2 n = 3*n+1; System.out.println(n); return F(n); >// This curly brace matches "opening brace 2" > // This curly brace matches "opening brace 1" else < System.out.println("Complete"); return 0; >> 

But that still isn't legal, and the reason isn't obvious. What happens here is that Java requires that you have a return statement in every possible path. And here's what the compiler thinks: If n > 1 , then you have an if statement if (n%2 == 0) . If this fails, it goes to the if statement if (n%2 != 0) . If this is also false, then it will drop down past the last else part, and it will get to the end of the method without returning anything.

Of course, you and I will look at it and say, that's impossible, because either n%2 == 0 or n%2 != 0 must be true. But that requires that we do some reasoning. Java compilers don't do that kind of reasoning, so it can't tell that one of those two if expressions must be true.

So fixing this also requires that you change

 > else if(n%2 != 0)  
 > else  

You don't need the if anyway--it's totally redundant. If we get here, we already know that n%2 != 0 .