wood burning stoves*
The moose likes Beginning Java and the fly likes Can you have a return statement in an if/else loop? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can you have a return statement in an if/else loop?" Watch "Can you have a return statement in an if/else loop?" New topic
Author

Can you have a return statement in an if/else loop?

Ashley Kin
Ranch Hand

Joined: Oct 18, 2011
Posts: 36
I need to returen either 1, 2, or 3 back to the main for tie, win, loss, but I get an error message saying "missing return statement."
Do return statements not work in if/else loops?

Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3071
    
  33

What if your code doesnt satisfy any of the if or else conditions? What will you return from the method? So you need to have a default return statement- when nothing matches you need to return some default value.


Mohamed Sanaulla | My Blog
Riaan Nel
Ranch Hand

Joined: Apr 23, 2009
Posts: 160

To expand on Mohamed's reply; look at this simple example. What do you think will be return if the weapon is not a gun, knife or club?


Also, you shouldn't refer to an if/else statement as a loop; it is a conditional statement. Loops are used to repeat a piece of code, whereas an if/else is executed only once.


"The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man." - George Bernard Shaw
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
You are probably better off creating an enum, like this:No messing around with unitialised states, and no breaking the method in the middle. Note you have a default value for the result, so you are regarded as losing if you enter featherDuster, or something else not recognised.
What the compiler was complaining about was that you have lots of if-elses, but there is still the possibility that you will have something which never fulfils any of the ifs, so you never return anything.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you have a return statement in an if/else loop?