How do I return a valid input from scanner?

I gave up. I'm trying to figure out why my code is returning the first (incorrect) value.

For instance:

public static String lastName() {

    System.out.println("Last Name: ");
    String lastName = input.nextLine();
    String dataCheck = "[a-zA-Z]{1,77}";
    Pattern pattern = Pattern.compile(dataCheck);
    Matcher patternMatcher = pattern.matcher(lastName);

    if(!patternMatcher.matches()){
        do{
            System.out.println("Incorrect input:\n"
                    + "1) Shorten the first name less than 77 characters;\n"
                    + "2) Only alphabet characters are allowed (no numbers or special characters.)\n\n"
                    + "Please enter Last Name: ");
            lastName();

        }
            while (!patternMatcher.matches());

    }
    return lastName;
}
public static void recall(String lastName){
    System.out.println(lastName);
}

What happens is if I enter an incorrect input, the scanner "stores" the first input and only uses it; if the input is correct, it continues. Research so far has told me to scrap the regex and just use input.hasNextLine(). Any help would be appreciated.

Jon Skeet
people
quotationmark

You're making a recursive call, but not using the result... so once you come out of the loop, you're just returning the lastName variable from the top-most stack frame If you change this:

lastName();

to this:

return lastName();

then it might work. It's not entirely clear to me, because the code structure is unclear to me.

Fundamentally, it's not clear why you're recursing and looping at the same time. That feels like a very bad idea to me. Work out what you want to do on iteration (probably: display options; read a line; check the line) and put all of that inside the loop. So something like (pseudo-code):

do {
    display-menu
    ask-for-input  
} while (test-to-check-it's-not-valid)

Additionally, I'd revisit your naming - something like getLastName() or readLastName() would be clearer for the method than just lastName() - particularly as you have a local variable called lastName within the method.

people

See more on this question at Stackoverflow