5.12 Problems and Solutions
Hello everyone in the last video, we used the Scanner class which allows a user to enter their name and age. But it can have problems, for example if a user enters a negative number. We’re going to test, we’re going to launch our program, for the year of birth I’m -20 and I enter a name and he says now that I’m 2041 that’s absolutely wrong. So what we need is to add a condition that checks if the year of birth is between 0 and 100 otherwise we display an error message for the user. After the variable age, I write the condition if age >= 0 && age <= 100, the interior of the condition we put It is that we will do now, this is to ensure that the user does not enter letters for the date of birth and for his we will use a method called «has next int» which will return a boolean. So just after the display «enter your date of birth» I make a variable boolean hasNextInt = scanner.hasnextInt(), so the method hasnexInt Will ask the user for an entry and check if it is an int otherwise it returns us false. What we need to do now is check if our boolean is true and if so we can continue with our calculations. So if (hasNextInt) And we copy it all to our close. That was all for this video, we just saw the types of errors that can be for our input and I tell you next time!