Adz
Adz

Reputation: 2847

Validating user input in Java (Scanner)?

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);
    }

}

Upvotes: 0

Views: 1760

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71019

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.

Upvotes: 3

Related Questions