File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trying to add a loop " Watch "Trying to add a loop " New topic

Trying to add a loop

Joey McGee

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: 75

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

Joined: Oct 01, 2001
Posts: 2968

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: 187

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 |
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46410
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:
subject: Trying to add a loop
It's not a secret anymore!