Albin13299
Albin13299

Reputation: 21

How do I add a alternative input to "exit" or "continue"?

I have done this:

public class Socialsec {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a Social Security number in the format DDD-DD-DDDD, where D is a digit: ");
        String userInput = in.nextLine().trim();

        String socSec = "(\\d\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)";
        Pattern ssNum = Pattern.compile(socSec);
        Matcher matcher = ssNum.matcher(userInput);
        if (matcher.matches()) {
            System.out.println(userInput + " is a valid social security number.");
        } else {
            System.out.println(userInput + " is not a valid social security number.");
        }
    }
}

I wanted to add the possibility to the user, either the user enters "continue" or "exit" to exit. I dont know how to add that to the statement, is it with a "while" statement? Because I want the option on both the true answer and the false answer. the "option" should always be there after displaying true or false.

SO example: "Enter "Continue" to continue and "Exit" to quit: "

Upvotes: 0

Views: 61

Answers (1)

acarlstein
acarlstein

Reputation: 1838

The easiest code would be something like this:

public class SocialSecurityValidator {

    public static boolean isSocialSecurity(String value){
        String socSec = "(\\d\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)";
        Pattern ssNum = Pattern.compile(socSec);
        Matcher matcher = ssNum.matcher(value);
        return matcher.matches();
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        boolean doExit = false;
        while (!doExit){
            System.out.println("Enter a Social Security number in the format DDD-DD-DDDD, where D is a digit: ");
            String input = in.nextLine().trim();
            if (input.contains("exit")){
                doExit = true;
            } else if (isSocialSecurity(input)) {
                System.out.println(input + " is a valid social security number.");
            } else {
                System.out.println(input + " is not a valid social security number.");
            }
        }
    }
}

I moved your social security regular expression into a method that does only that.

Then, I created a boolean variable to keep the loop alive until the user types exit.

If you have any question about the code let me know.

Upvotes: 1

Related Questions