Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trying to add a loop

 
Joey McGee
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to add a loop to my program to varify the meal code and if it's not valid, continue to prompt the user until it is. The meal code goes from 1-4. Below is my code so far:



 
Aj Prieto
Ranch Hand
Posts: 75
Android Chrome Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just ask for mealCode again by adding:

inside of your while loop.

What are the following lines for?


Edit: Also, take a look at the boolean statement for you while loop, it's not doing what you think it's supposed to be doing.
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Having the loop at the end of the code isn't going to help you, and changing the user's choice (by subtracting 5) also seems unlikely to make the user happy. You should put the loop around where you ask the user for the meal code. Try to set up the loop so you will enter it once no matter what, enter it again if the input is invalid, and exit it if the input is valid.
 
Rajdeep Biswas
Ranch Hand
Posts: 221
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You can replace this with:


PS: This is just a sample. You can optimize it further! Yes!!
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are mistaken trying to validate your meal code inside your main method. A main method is intended for starting your application, and you should restrict your methods to doing one thing. I think you should write yourself a utility class with such methods in. You can find an example here. You can write another method (in the same utility class) which validates the input is in the required range, (is it 1…5?) and prints an error message on screen. Those two methods call each other, so you are not duplicating code. Remember all members of utility classes are static.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic