English subtitles

← Input Validation - Intro to Java Programming

Get Embed Code
5 Languages

Showing Revision 5 created 05/24/2016 by Udacity Robot.

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