0

What I would like to do:

  • restrict user input to letters only (lowercase and caps)
  • error message on incorrect input
  • loop until correct input

Quite a few sites with similar questions suggested regular expressions, patterns, and matchers. I had at look at the API, and it confused me a lot...

Here's what I tried.

public class restrictinput {
    public static void main (String args [] ) {
        Scanner sc = new Scanner (in);
        System.out.println ("Enter  blah ");
        String blah = sc.nextLine();
        Pattern userInput = Pattern.compile("^[a-zA-Z]+$");
        Matcher inputCheck = userInput.matcher("blah");
    }
}

This compiles, but I'm not sure if it's the correct/best way to do it. But, if I enter a different character type, it just executes the rest of the code.

How do I only make it execute if the correct character type is received, and what should I use to make the error known to the user?

If the code given is wrong, what should I do to change it?

2
  • You probably mean 'loop until correct input', in which case where is your loop? Commented May 15, 2012 at 15:19
  • both done. like i said this is new territory for me. Commented May 15, 2012 at 15:28

2 Answers 2

2

This seems like homework, so I don't want to give away too much, but you want to look into the if statement as well as the while or for loops. This will conditionally execute code if certain criteria are met.

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

Comments

1

Okay so there are a couple things here you need to fix. The first thing I noticed is that you want

userInput.matcher(blah);

not

userInput.matcher("blah");

because you are matching the string, not just "blah"

Now for the bulk of your question. The first thing you need is to look at the Matcher object. Specifically look into Matcher.find().

The second thing is that you need to add some sort of a conditional loop to your code so that it keeps asking for input. Maybe something like:

bool result = true;
do {
    String blah = sc.nextLine();
    Pattern userInput = Pattern.compile("^[a-zA-Z]+$");
    Matcher inputCheck = userInput.matcher("blah");
    result = //boolean check from your matcher object
    if(result) {
        //Complain about wrong input
    }
} while(result);

1 Comment

bool result = true; do{ String blah = sc.nextLine(); Pattern userInput = Pattern.compile("^[a-zA-Z]+$"); Matcher inputCheck = userInput.matcher(blah); if(false) { System.out.println("wrong input"); } while (true); something like this?

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.