• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Bartender
Posts: 3225
34
IntelliJ IDE Oracle Spring Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 160
IntelliJ IDE VI Editor Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic