[英]Validating user input in Java (Scanner)?
我正在嘗試獲取一個使用Scanner方法的程序,以檢查無效輸入,例如數字和特殊字符(即!@£$%^),並在輸入時簡單地打印出錯誤。 我嘗試使用matchs()方法修復它,但是它仍然可以打印出我鍵入的所有內容! (即使有特殊字符和數字)
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);
}
}
您應該在正則表達式的前面和后面添加一個。*。 就像是:
if (words.matches(".*[^a-zA-Z0-9 ].*"))
這個想法是,您應該允許在要忽略的字符前面或后面加上任何字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.