Elevator Demo with Input Validation – Intro to Java Programming

So here’s the original elevator demo, where we read in an integer, or we’re hoping it’s going to be an integer, and then we use it here for that first demonstration of a new statement. Our task is to make sure that we get a valid integer here. Someone was kind enough to supply us with the bits and pieces that we need. Here is the check where the, the user mistakenly enters 13. Whether the floor is less than 1 or greater than 18. And finally, where that’s not an integer at all. Our job is to put these together in the right order. Now, the first 2 checks already assume that the user entered an integer. So we should use the sur check first to test for that. Let’s cut it out, and paste it into the main method, and fix up the flow. So, we have our scanner, we’re prompting the user to type something in, and now we’re checking what the user types. And if that’s successful, then we call nextInt. And that gets us to where we were here. So, everything that’s down here needs to get inserted here. Let’s do that. So, if the user entered an integer, we grab the integer and we do our computation. Let’s move on to the other tests. Here they are. Again, I’ll cut them out. So, these one’s only make sense after I have read in the next input as an integer. So I’ll paste them in here. So if the floor is 13, I print an error. If it’s less than equal 0 or greater than 18, I print an error. this isn’t really going to work because I’m printing the error and then I still continue with all of these things. What I really need to say is if this error happens, print the error, else go on here. Let me do that. So I have enclosed all of the original action inside this else. Now peaking up, there still is a bit of an issue with control flow. The floor is 13, then it does this, and then in all cases, whether or not it’s 13, it makes this check. So we also want to put an else in here. So first we check whether the number is even an integer. If so, we check whether it’s one of these two special situations. And finally here we know that it is a good input, and we do our regular thing. Note that we have three levels of nesting. This if contains this if, and the else branch here contains another if. C’est la vie.

Leave a Reply

Your email address will not be published. Required fields are marked *