Basic User Input Validation in Java

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to another Java video tutorial in this tutorial we are going to extend on some of the work that we did in the last video which was all about handling basic runtime errors in Java using a try and catch block so a link to the video somewhere around the screen here somewhere and there'll be a link to it in the description down below so the idea is that we're going to use a try and catch block to do some user input validation so one of the things that can happen when we're taking input from the keyboard is that we might want the user to enter in an integer value and by mistake the user might enter in maybe an alphabetical value like the letter A or something like that and that can cause a runtime exception in our program so obviously we don't want that to happen we want to be able to validate user inputs make sure that the input that the user is giving us through the keyboard is the input that we expect or that the program expects so we can use try and catch blocks in order to do that so what we'll do is we write a very simple program to start off with and I take some user input and we'll see how some incorrect input can actually cause our program to crash and then we'll go about fixing that using a try and catch block okay so let's write some code alright so what i've done is i've already set up a class called input test and i've imported Java dot util dot scanner because I'm going to be using the scanner class to take input from the keyboard so and basically what we're gonna do is take in some integer input from the keyboard so I'll need an integer variable to do that so I'll say int and num for example and I'll initialize it to zero I'll give it an initial value and then what do I want to do well I want to probably prompt the user to give me some input from the keyboard so let's do that so let's say prompt the user and we'll give out a little message on the screen to say system dot out dot print and I'm using a print statement not a print AirLand statement because I want the user input to be on the same line as the message so just a print statement not a println so I'm gonna say enter an integer value okay so that's prompting the user and then what I want to do next is I want to actually read the value in from keyboard so read in value and the way I'll do that is I'll use a scanner class and to do that so what I'll actually do is just before I prompt the user I'll set up the scanner class I'll do that up here and set up the scanner so I'll say scanner in equals new scanner so we're creating a scanner object and they want to take input from the keyboard so I'll say system dot in and so that should set up our scanner for us so now and I want to read in a value I can say in well I want my number to get the value so I'm gonna say no equals n dot how do I read in of an integer value well it's next int that will read in an integer value from the keyboard so maybe in my comment I should say read in integer value so I read in the integer value from the keyboard and then what do I want to do well I just output the message I'll just output that number to the screen to show that we have indeed entered in a number it's been stored in our gnome variable and we can just see that on the screen so I'll put the number entered by user until I'll just have a system dot out dot println and i'll say you entered the number and we put the number which is stored in the variable nome ok so that's pretty much it that's our program so we've used the scanner class we've set up the scanner class we've prompted the user to enter in an integer value so the user knows what type of value we're looking for we've asked them for an integer value and then we read in the value from the keyboard using nome equals n dot next int so our number variable will be given the value that's read in from the keyboard and then we just have a system output message down here just to print out the number to the screen so very basic stuff we will save that and compile it over here so I'll say in my terminal window Java C input Java hopefully there are no syntax errors and the learner any syntax errors so let's run the program so Java input input test so we are prompted to enter in an integer value okay everything's good so far and if I enter in an integer value if I enter in the value oh let's say that's re-enter in 100 and I press the Enter key on the keyboard then we got our message you entered the number 100 and everything looks absolutely fine and in that case the program didn't encounter any problems on it executed and did what it was supposed to do ok let's clear the window for a minute and let's run the program again this time and what I'm going to do is show you how it can very easily and open a situation where we have a runtime exception and the program will crush if the user enters in an incorrect value in other words a value that we were not expecting so I'll run the program again and as you can see we have our prompt enter integer value and if I enter in value a for example and hit enter you'll see we get a problem so we have an we have encountered a runtime exception so not a syntax error and not an error on compilation the program has encountered an error while it was executing on the error that it encountered was it expected to read in an integer value from the keyboard and I typed in an alphabetical input the letter A and so it crashed all right so obviously that's a bad situation we don't want that to happen you know that could very easily happen by someone pressing the wrong key on the keyboard and we definitely don't want our system to crash just because someone typed in an A instead of our one or something like that so we're gonna have to be able to handle those situations and that's where user input validation comes in so we want some way to validate the input that the user has given us on the keyword to make sure that it is the type of value that we were expecting and if not then maybe we want to ask the user oh look you know please try again enter in another value and you know we want to be able to handle that in a kind of graceful way and we definitely don't want our program to crash because someone typed in the wrong value so if we have a look at the error that we're getting here you can see that it's an exception it's a runtime exception and the error the name of the error that we're getting is called an input mismatch exception so what that error is telling us is just as I've described there and the input that we typed in the input that the user typed in was the letter A we were expecting an integer our program was expecting an integer so there's a mismatch between the data we're expecting an integer user typed in a letter so there's a mismatch so the the error message is quite descriptive in this case it kind of tells you what went wrong okay so how are we going to handle this all right we're going to use a try and catch block but there's a little bit more that we need to do on top of just using a try and catch block because we have to think about what way we want to handle this situation if the user enters in an incorrect value do we want the program to just stop and for the user to have to run the program again probably not a better way to handle it would be to just re prompt the user hey look you know you entered in the wrong value and please enter an integer value and just continue to do that until they enter in the value the type of value that we're looking for so this is a little bit more than just a trying catch block involved here and we'll work through the process of building all of that user input validation into our code in the next few minutes so the very first thing that I'm going to do is just kind of think about the type of input and that we want okay so just as an example if we wanted some integer input okay well what our integer as well and you know they're all the numbers all the negative numbers on the positive numbers including zero as well aren't they so like we could have minus three minus two minus one zero one two tree you get the message and on we go so they're the integers right and what other types of input could we want well sometimes we want decimal numbers right and we usually use doubles for that so the types of input there are like 0.1 25.5 for what are their values could we think about here maybe 0.001 or something like that so we have decimal type numbers and the other types of input that we typically and take our kind of string input right so and maybe we want someone to enter in their name so maybe they want to enter in their personal details on in a pretty into a program so we might need them to enter in their name so their name could be Steven and maybe we might want them to enter in their address or their favorite color or something like that and or the name of their first car or something or whatever it doesn't matter but it's a string value okay know the things about the thing about strings is actually that and you know string values are numbers letters on a mixture of numbers and letters so for example and I could ask the user to type in a password okay so their passwords could be one a or maybe one a lowercase J 99 lowercase K maybe even an exclamation mark on an on symbol on an Asterix and then maybe an @ symbol or something like that so the password can be made up of a combination of numbers or per case letters lowercase letters and special symbols like exclamation mark or the on symbol or yacht symbol so if we get the user to enter in a string it can be a combination of lots of different things so that's actually kind of a safe way to approach this problem is that what about if we get the user to if we if the input that we take in is a string and then what we can try and do is try and convert that string into a number if it's an integer that we want we could try and convert that string into an integer number or we could try and convert that string into a double or if it's a string that were interested in taking in from the keyboard we can just accept that in as a string because the string can contain anything right so we don't really have any particular validation problems around the string unless you wanted them to enter in date or an email address or something like that and then you might do some extra validation on the string let's keep a basic for the moment and let's think about those basic types an integer a decimal number or a double and then string input so the way we're going to handle this is we're going to be clever about it and we're going to actually take in a string from the keyboard and then we're gonna try and convert that string to the type that we require okay so as we work through the code you'll see that it actually makes sense and it's a nice way to handle this user input validation problem okay so the first thing that we want to do is we have our number and I want to now take in a string from the keyboard so I'm gonna need a string so I'll say string and I'll call my string STR input I don't need to initialize it with it with a value or anything like that I'm still going to have my scanner class I'm still going to need that and I'm going to also need another variable here and you'll see why in a minute I'm going to introduce a boolean variable called valid and I'm gonna set valid equal to false the reason why I'm going to introduce this boolean variable is because I'm going to use a loop to actually keep on asking the user for input if they get it wrong so that's how I'm going to actually continuously drive the program until the user enters in an acceptable value and then I can continue on from there so I'm going to setup a boolean variable and I'm gonna Hollett valid and they're going to initialize that boolean variable to false to begin with okay so what I'm going to do next is after my M where I declare my scanner and class R my scanner object I'm going to create a while loop and I'm gonna say while valid equals false okay so the idea is here is keep looping until valid input okay so we want to keep on looping until the user enters in a valid input and then if they enter in a valid input the loop will break so in other words another way to say that is as long as they keep on entering in an incorrect value we want to keep on asking them to enter in the correct value so that's the way we're gonna do we're gonna use a while loop to do that okay so inside my while loop what am I gonna have inside my while loop well the first thing that I want to do is I want to prompt the user to enter in a value right what kind of value do I want the user to enter in I still want them to enter in an integer so I want them to enter in a number so my prompt isn't going to change it's still gonna be the same prompts the user on the user is going to enter in an integer value okay so that's fine and the next thing that I want to do is I want to grab some input again from the keyboard alright so I'm not gonna use this read in int reading an integer value I'm gonna get rid of that oops got rid of my while loop bracket there don't do that so I'm gonna say system dot out dot print enter in an integer value now here's the thing I'm asking them for an integer value but what I'm actually gonna read in from the keyboard is a string value okay so little bit confusing but you'll see where we go with this now in a minute so we're gonna enter in a string value so want to grab input on keyboard okay so we're gonna grab input from keyboard and better spell grab correctly there so grab it from input from keyboard so I'm gonna use my string variable to do that so I'm gonna say STR input equals in dot how do I read in a string from the keyboard I use the next line and method of the scanner class all I'm gonna say next line so that's gonna read in a string okay as I said a little bit confusing but you'll see where we go with this now reading in a string as I said earlier on a string can contain letters or per case lower case numbers special symbols like exclamation marks it can contain a mixture of all those different inputs even you know decimal numbers we could still we could have those in a string okay so string is probably the most flexible datatype in terms of user input and that's the reason why we're taking this approach of using a string to take the input but what we're going to do next is we're going to try and convert the string that the user has entered into the data type that we require and in this case that's an integer value so the next line of code is going to try and convert the string into an integer okay so how do we do that well we are going to use the integer class in Java okay and that's gone too that has a special method that tries to take a string and hopefully if the string has the right content it can convert that to a number will give us back a number so this is where am I try and catch block comes in because what about if the string didn't contain just a number what about if the string contained a letter and a number or a symbol and a number are a decimal point and a number and letter or whatever when it tries to convert it to an integer it's going to fail because it's not in the right format so this is where I need to introduce the try and catch block to try and capture that runtime error that might occur and then I can handle that gracefully and I can re prompt the user to enter in and the appropriate data type again so this is where my try and catch block comes into play so I'm gonna say try I'm gonna have a try block okay um and I'll actually just put a little comment in here I'll say try to convert string oops try to convert string to int so that's what we're going to attempt to do in this try and catch block right as well as my try block I'm gonna need a catch block so let's just put that in for a moment I'll just kind of put a blank one in remember for every try block you need a catch block an associated catch okay so in my try block what I'm going to do is I'm gonna try and convert the number and I'm gonna say numb so that's my integer variable that I declared earlier on but this is the number that I want to actually take in the input into so I'm gonna say numb equals okay now I'm going to use a special class in Java called integer now this is different from a basic int datatype an integer the integer class is actually a class unlike an creation like an integer object as well and but what I want to do is use a method in the integer class a static method in the integer class to parse and to try and convert the string to an integer value so the way I do that is I say integer dot parse int okay so integer is a class in Java an integer datatype class in Java and the method that I'm calling on it is parse int so what it's going to try and do is it's gonna look at the contents of the string that I'm gonna give it and it's gonna try and convert or parse that content into an integer number okay so I need to give this parse int string as an argument so what am I going to give it as an argument well I'm going to give it this string value that I read in from the keyboard right so the user actually they think they're entering in an integer but they're not they're entering in a string really I'm taking the input in as a string and then this is gonna try and convert that to an integer so the input that I need to give it here is as to your input okay so this is the key to how this is going to work that line of code num equals integer dot parseint and I give the parse int method the string that I read in from the keyboard if the string is in the right format if it's just normal integer numbers it will work if it's not if it contains a letter or some other type of mixed input it's going to fail and it's gonna cause a runtime exception okay now what type of exception is it gonna cause well it's actually going to of another bit of work to do in this try block right so if this if this line of code works okay if that line of code executes we won't have a runtime exception and the code will just continue on so the next line of code after that this is really important and I almost forgot it I need to set my valid equal to true I remember this boolean variable that I said Oberle are on I initialize that the false initially and then my while loop said while valid equals false so it's gonna continue looping around well if this integer dot parseint method works and we convert the string to a number we will not cause a runtime exception and the next line of code after that will execute and valid will be set to true and it will break the loop okay so that this is where the loop actually breaks if we get to this line of code if we get to this valid equals true well then the loop will finish okay so if the user gets it right first time if these are enters in an integer number the first time will only actually go through one execution of this loop if they got it wrong the first time and then got it right the second time will go through two iterations of this loop they continuously get it wrong and enter in letters instead of numbers will continuously keep on going around and round the loop until they do get it right okay so that's important then the next thing what I need to do is finish off this Koch block so the name of the exception that we're going to use here that the exception that we're going to try and catch is called a number format exception so number format exception and I'm going to call that exception II and all I want to do in this case is I don't want to do a stack trace or print down a met and an error message from the system what I'd like to do is I'd like to say system dot out dot println and i'll say error enter an integer value so the user is going to get an error message but it's going to be a meaningful error message that I'm actually going to output and it's going to be informative it's going to say look there's an error and you need to enter in an integer value you obviously isn't entering an integer value so you need to enter one otherwise we can't continue so that's all that we're going to do in the catch now remember this trying cottages inside a loop and loop will keep on going as long as and the user gets it wrong once they get it right then valid will be set to true the loop the guard on the loop will fail and the loop will end and our program will just continue on as normal okay so there's a there's a good bit going on here and there's a few steps involved in this process in order to validate the user input so let's first of all compile the program we'll run it and we'll see what happens so I'm gonna save it let's go over here and that's wrong or let's compile our program first of all hopefully I don't have any errors no syntax errors okay that's good we're gonna run it now and the first time we run it we'll get the input correct okay so we'll say Java input test and it says in enter an integer value so we got our prompt I'm going to enter in the value 100 as I did before and we get an error message to say you entered the number 100 okay so everything worked that time because I was actually entering in a string the input that I put in here this 100 that I entered was actually being taken in as a string value and then we converted that string value to an integer using the line of code here num equals integer that percent okay so that line of code is taking this input that I thought I typed in here this 100 and it's taking that it's a string but it's trying to convert that string into an integer value now did it work yeah sure it did because look at what I entered I entered in the character one I entered in the character zero followed by another zero are the digits or should I say so the digit one zero and a zero now can you convert that into an int yes you can because it's the right format so let's run the program again and this time we've got it wrong okay so we'll run the program again again we get enter an integer value and this time what I'm going to do isn't gonna type in the letter a and hit return okay no crush which is good okay but what do we get we get an error message to say error enter an integer value so that's where our try and catch block is coming into play the try had contained the code that was going to maybe possibly cause the runtime error and the catch block has our error message in the event that the user enters in some other and non integer type value so we got our error message and again the loop has come into play here because we are now reap romped it again to enter in an integer value what about if I got it wrong again let's say I type in the @ symbol this time so I'll type in the @ symbol and hit return so again we go around the loop again because the parse int method failed the @ symbol cannot be converted to an integer number so that runtime exception happened we caught the exception print it out the error message and we're back around the loop again re prompting the user to enter in an integer value so this time I'll get it right and I'll enter in 200 and I'll hit return and as you can see and the digits two zero zero in a string can be converted to an integer number so our parse int method has succeeded that time and converting that string to an integer and our valid was set so the guard on the loop now is broken the guard on the loop evaluates to false and the program just continues on and we get our little output message at the end of the program to print out the number and that we typed in which was 200 okay so if we have a look at this little example here we've shown that you can use a try and catch block along with a loop and some other little bits and pieces to validate user input and the way we approached it was we kind of asked the user to enter an integer but we treat their input as a string and then we see can we convert that input into the datatype that we actually require which is an integer and we use that loop mechanism and the boolean variable to keep looping around until the user actually enters in the correct input so this is a nice way to handle a user input validation but as you'll see there's quite a few lines of code involved in this on a loop and a trying catch block so would you would you have to repeat this code every time you want the user to do some input no not really there's a better way to do this and we're gonna wrap all this functionality up into a reusable piece of code called a keyboard class so in their next video what we'll do is we'll take the work that we've done here we'll take this user validation and code that we've written here and we'll wrap it up in a class that will provide us this functionality that we can use anytime we want in any of our programs and we'll be able to do user input validation without having to write all of these lines of code again and again and again so that's in the next video and so stay tuned for that that's gonna take this user input validation to the next level and make it really really usable so again if you've liked this video please subscribe to the channel and give the video a thumbs up hit the notification about to make sure that you get the next video cuz otherwise you're gonna have to type all of these lines of code and every time you want to do some user input and please leave some comments down below as I said all of the feedback that I get on the videos really helps me at least it lets me know that people are finding me useful and once again I'll leave a link to the previous video in the notes below this one so you can go back and have a look to see how try and catch blocks actually work and a little bit more detail so that's all for now thanks a lot stay tuned and I'll see you again next time
Info
Channel: Stephen Sheridan
Views: 6,032
Rating: 4.9130435 out of 5
Keywords: Java, Tutorial, Coding, User input validation, Validation, Try and catch, Runtime error, Error handling, Input, Keyboard input, Java Scanner, Education, Programming, Fundamentals, Lesson
Id: dW-aWDLV44c
Channel Id: undefined
Length: 33min 44sec (2024 seconds)
Published: Thu Apr 16 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.