How to make the user give you the right amount

in programming •  4 years ago 

Let's assume you are writing a program in which user can input the amount of meat they have, and you give them what recipe they can cook. Of course, the user should not give you a negative number. But maybe they do (perhaps by mistake, or on purpose for QA). You shouldn't let them since the program will show "Sorry, we don't have any recipe for your amount of food" instead of "The amount can not be negative".
So, most beginners use "if" statements here:

if input less than 0, ask the user to give you another number

But there is a problem here! let's assume the user gives you -1. Then the program will ask them to input another number. What if they give another negative number (again, for QA)? The if statement already passed and will not run again. So, the problem is not solved.
We should use "while" instead:

while input is less than 0, ask the user to give you another number

The user will stuck. They have no other choice than to input numbers as much as they give a positive number.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!