Hello guys!
this is the best forum for Java, and you guys are the best!
now >>> the question...
i mdae a method, and a for loop inside the method:
- public String go(String width)
-
{
-
for(i=0; i< 300; i++)
-
{
-
if(blablabla)
-
{return "a";}
-
}
-
}
this is the example of the code, when i try to compile this application i have error: "missing return statement"....
so i guess i have to write the return statement after the for loop, but than it wouldn't be the same (and it would not consider my IF condition) ! please help me!
Suppose the expression 'blablabla' is never true: the loop completes and then
nothing will be returned. Maybe *you* know that 'blablabla' will always be true
somewhere in that loop but the compiler isn't that smart, i.e. it can't figure that
out without actually executing the code it is compiling.
Sometimes these things happen and you have to add another return "string"
statement at the end of the method as well, although *you* might know that the
code will never be reached.
If, on the other hand 'blablabla' turns out to be always false you also must put
another return "string" statement after the loop.
On the other hand: some folks like the 'one return statement' policy and they'd
break out of the loop after setting a flag or similar if 'blablabla' happens to be true.
At the end of the method they'd test that flag or similar condition and decide
what to return. I find that approach a bit 'mechanic'.
kind regards,
Jos