This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Trying to add a loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trying to add a loop " Watch "Trying to add a loop " New topic
Author

Trying to add a loop

Joey McGee
Greenhorn

Joined: Nov 22, 2012
Posts: 27
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

Joined: Sep 28, 2012
Posts: 72

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.


Da mihi sis bubulae frustum assae, solana tuberosa in modo Gallico fricta ac quassum lactatum coagulatum crassum.
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2841
    
  11

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

Joined: Mar 26, 2012
Posts: 186


You can replace this with:


PS: This is just a sample. You can optimize it further! Yes!!


The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38087
    
  22
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trying to add a loop
 
Similar Threads
Alternative if statement & toString
Creating an Array list
Crazy date program
parse a string
learning how to use classes