0

I'm trying to get a program which uses the Scanner method, to check for invalid inputs such as numbers and special characters (i.e. ! @ £ $ % ^), and simply print out an error if they're entered. I've tried to fix it, using the matches() method, but it still prints out everything I type in! (even with special characters and numbers)

private static void input(String s) 
{
   Scanner userInput = new Scanner(System.in);
   String words;
   System.out.println("Enter your words: ");
   words = userInput.nextLine();

if (words.matches("[^a-zA-Z0-9 ]")) 
{ 
    System.out.println("Error, no number input or special character input please: ");
}

else 
    {
        System.out.println(words);
    }

}

1 Answer 1

3

You should add a .* in front and behind the regex. Something like:

if (words.matches(".*[^a-zA-Z0-9 ].*")) 

The idea is that you should allow any preceding or following character to the ones you want to ommit.

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

1 Comment

And add a ! to boolean clause (to output error message only when non-desirable symbols are present).

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.