1

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

  1. the user input digits only
  2. they did the correct number of digits and
  3. 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!

3
  • Is it compulsory to use regex? Commented Oct 20, 2018 at 9:00
  • Date/time validation is better done with appropriate date/time APIs Commented Oct 20, 2018 at 9:03
  • @RoshanaPitigala No it isn't compulsory to use regex. It is just what I found online that seemed to satisfy all my validation requirements. Commented Oct 20, 2018 at 12:32

2 Answers 2

1

If you want to use regex,you can try this

    while(!(Pattern.matches("(0)[1-9]{1}|(1)[0-2]",month)))
    {
           System.out.println("Enter again \n");
           month=input.next();
    }

For this code to work you need to include regex package, by using this at the beginning of your program

  import java.util.regex.*;

Our regex is in two parts "(0)[1-9]{1}" , this will first make sure that the string contains "0" and then any digit between 1-9. And "{1}" will make sure that it occurs only once.

Similarly write the code for day and year,if required.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This worked and you made my regex look nicer and shorter :)
0

Use DateTimeFormatter something like this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy");

try {
    LocalDate date = LocalDate.parse(input, formatter);
} catch (DateTimeParseException e) {
    // Thrown if text could not be parsed in the specified format
}

1 Comment

Thank you for the info on the DateTimeFormatter. I didn't know about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.