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?
Okay so there are a couple things here you need to fix. The first thing I noticed is that you want
not
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: