If-else block in nested loops - compiler complaint: I need a return statement

How do I do this job? It says that I need to add a return statement, but I have one.

public boolean clockFactCheck(int a, int b){ for (int i = 0; i <= 276; i++){ for (int h = 0; h <= 55; h++){ if (a == i + 186 && b == h + 133){ return true; } else { return false; } } } } 
+1
source share
6 answers

The code provided cannot reach one of return for any input a,b and the one the compiler complains about.

In fact, in your case, if-else will be achieved with the very first iteration - unfortunately, something that the compiler cannot output. Thus, he follows the path of conservation and eliminates this error.

Comment: Therefore, it doesn't seem to make much sense in your loop, since it will not be named at all, but will stop at the first iteration i==0 and h==0 . Did you want to code something like that?

+3
source

You don't have a return statement after the for loop, but even then h ++ is dead code because it will never go past the first iteration.

0
source

Place the return statement outside the loop. (declare a boolean in your function, change it and return it at the end)

0
source

I assume that the compiler is not smart enough to realize that there are no codes around the loops.

If this is real code, simplify it to

 return (a == 186 && b == 133); 

If this is not real code, maybe there is another way that does not return (if you insert an error), or there is actually a compiler error or restriction. At some point, the problem of stopping will bite you, and the code is too complicated for the compiler to understand.

In the latter case, I would put

 throw new RuntimeException( String.format("should never get here (a = %d, b = %d) !",a,b)); 

in the last statement.

This makes both compilers happy and does not introduce a return value of "undefined" for a case that should never happen, or if it does, I did not think.

0
source

Java requires each path to return a value. The compiler could not judge whether the call would return the path. If your code is as follows:

 public boolean add(){ for(int i=0;i<100;i++) if(i==5000) return true;} 

add function will not return value. Instead, an error will occur.

0
source

Oh yes, I'm bad, I'm sorry it was a stupid question when I posted it. I understood the answer to my problem. If you made the same stupid mistake as me, this fix

 public boolean clockFactCheck(int a, int b){ for (int i = 0; i <= 276; i++){ for (int h = 0; h <= 55; h++){ if (a == i + 186 && b == h + 133){ return true; } } } return false; } 
0
source

All Articles