-
Title:
Input Validation - Intro to Java Programming
-
Description:
-
Well, they're actually both right, let's see why. Let's look at the blue code
-
first. When we start, the value is 100. We go to the loop, value is greater or
-
equal than 100. In fact, we've set it, to make sure we enter the loop. We ask
-
the user to enter a value. Let's say the user is uncooperative and enters 200,
-
then we go back up. Now, the value is still greater or equal than 100. And we
-
go back in the loop. That was the whole purpose really, of this while loop. We
-
wanted to keep asking the user while the value is greater equal than 100, since
-
our target is to get a value less than 100. Remember, the while condition is
-
always the opposite of the target. So now, let's say the user is doing better,
-
enters 99. I'll go back to the top of the loop. 99 is less than 100. And we
-
follow through, so it worked. So this one was a good solution. Now, let's look
-
at the black solution. This one is a little different, we ask the user to enter
-
a value less than 100 and let's say they do, then now comes the loop. This loop
-
is never entered. And in this case we get the right behavior. So, let's look at
-
another situation where the user doesn't makes a mistake first. So, we're again
-
at the top. We ask the user to enter a value less than 100. The user enters
-
200. Now, that's greater or equal with N100, So now, we get into the loop and
-
we ask the user again and say no if they give the right answer. Then we go back
-
to the top and now we're satisfied, so this also works. But both of the
-
solutions are a little unsatisfactory. Look at the first one here. We have this
-
trick where we're setting the value to an artificial value not to a user input
-
so that we enter the loop the first time, it's a bit ugly. The second one we
-
repeat part of the code. Look at this statement here and the statements here,
-
they're exactly the same statements and we need to repeat them because we first
-
need to get the user input before we can see whether it's any good. And then,
-
we need to keep bugging the user until it's any good. That repetition is also,
-
somewhat undesirable. There is a Java statement that can take care of this
-
issue.