Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #39010
| Newsgroups | comp.lang.java.programmer |
|---|---|
| Date | 2019-07-18 07:51 -0700 |
| References | <67615856-0be2-4c3f-ae4c-c9f3cb379451@googlegroups.com> |
| Message-ID | <db910e06-39dd-42c3-991f-a2cb23dbcadb@googlegroups.com> (permalink) |
| Subject | Re: Java missing return statement question... |
| From | Eric Douglas <e.d.programmer@gmail.com> |
On Thursday, July 18, 2019 at 9:30:03 AM UTC-4, cda...@gmail.com wrote:
> I don't quite understand why something like the following gives a missing return statement.
>
Always make sure every branch returns a value if the method return is anything other than void. A compiler will complain about the impossible branch.
public static boolean test() {
if (1 != 2) {
return false;
}
}
"This method must return a result of type boolean"
else is not needed if the condition will otherwise exit the method.
Anything after if with no else is your else
public int withoutDoubles(int die1, int die2, boolean noDoubles) {
if (die1 != die2) {
return die1 + die2;
}
if (noDoubles == true) {
if ((die1 == die2) && (die1 != 6 || die2 != 6)) {
return (die1 + die2) + 1;
} else if (die1 == 6 || die2 == 6) { // this if had no else
return die1 + 1;
} else { // impossible condition??
throw new Error("how did we get here??");
}
} // else { // all other branches left the method? this is not needed
return die1 + die2;
// }
}
>
> But something like this this doesn't..
>
public int blueTicket(int a, int b, int c) {
int ab = a + b;
int bc = b + c;
int ac = a + c;
if (ab == 10 || bc == 10 || ac == 10) {
return 10;
}
//ab - bc = 10;
//ab - ac = 10;
if ((ab - bc) == 10 || (ab - ac) == 10 ) {
return 5;
} // else { // all other branches left the method, else not needed
return 0;
// }
}
> I both cases the return statement is in both the if and else clause.
just not in the implied else
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Java missing return statement question... cdalten@gmail.com - 2019-07-18 06:29 -0700
Re: Java missing return statement question... Andreas Leitgeb <avl@logic.at> - 2019-07-18 13:44 +0000
Re: Java missing return statement question... cdalten@gmail.com - 2019-07-18 06:54 -0700
Re: Java missing return statement question... Eric Douglas <e.d.programmer@gmail.com> - 2019-07-18 07:51 -0700
Re: Java missing return statement question... Eric Sosman <esosman@comcast-dot-net.invalid> - 2019-07-18 13:47 -0400
csiph-web