I know there have been lots of questions on input validations for Java, but no matter what I read, I just can't seem to get this to work. I would like a user to input birth date as (MM DD YYYY). I wanted to validate that
- the user input digits only
- they did the correct number of digits and
- the digits fell within the correct range.
My first attempt I had int variables, but I couldn't seem to combine a hasNextInt() with the digit length and range. I then saw a post saying to do String variable and then use Integer.parseInt(). I thought this would work well if I used (!month.matches("0[1-9]") || !month.matches("1[0-2]") because it seemed to satisfy all of my validation wishes. I tried this in a while statement, but it fell into an indefinite loop. I then tried to change that code into an if...else statement and surround it with a while(false) statement. However, it now throws an error instead of going to my statement that says fix your mistake. Here is what my code looks like for the moment:
import java.util.Scanner; //use class Scanner for user input
public class BD {
private static Scanner input = new Scanner(System.in); //Create scanner
public static void main(String[] args){
//variables
String month;
int birthMonth;
String day;
int birthDay;
String year;
int birthYear;
boolean correct = false;
//prompt for info
System.out.print("Please enter your date of birth as 2 digit "+
"month, 2 digit day, & 4 digit year with spaces in-between"+
" (MM DD YYYY): ");
month = input.next();
//System.out.printf("%s%n", month); //test value is as expected
day = input.next();
year = input.next();
//validate month value
while (correct = false){
if(!month.matches("0[1-9]") || !month.matches("1[0-2]")){
System.out.println("Please enter birth month as "+
"a 2 digit number: ");
month = input.next();
//System.out.printf("%s%n", month);
}
else {
correct = true;
}
}
//turn strings into integers
birthMonth = Integer.parseInt(month);
birthDay = Integer.parseInt(day);
birthYear = Integer.parseInt(year);
//check values are correct
System.out.printf("%d%d%d", birthMonth, birthDay, birthYear);
}
}
Any help would be greatly appreciated. I would also like to try to do this validation without any try/catch blocks as those seem too bulky. Thanks!