在Java(扫描仪)中验证用户输入?

时间:2013-02-03 17:49:22

标签: java

我正在尝试使用扫描程序方法来检查无效输入,例如数字和特殊字符(即!@£$%^),如果输入则只输出错误。我尝试使用matches()方法修复它,但它仍打印出我输入的所有内容! (即使有特殊字符和数字)

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 个答案:

答案 0 :(得分:3)

你应该在正则表达式的前面和后面添加。*。类似的东西:

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

这个想法是你应该允许你想要忽略的任何前面或后面的字符。

相关问题