File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Ashley Kin
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 3159
33
Google App Engine Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Riaan Nel
Ranch Hand
Posts: 160
IntelliJ IDE Ubuntu VI Editor
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic