我是Java新手,我想知道如何检查用户是否仅输入字母作为其姓名。如果还没有,请再次询问他们的名字。

System.out.print("Welcome - What is your family's surname? ");
familySurname = keyboard.nextLine();
while (familySurname.isEmpty())
{
    System.out.print("Invalid name - What is your family's surname? ");
    familySurname = keyboard.nextLine();
    if (familySurname.matches("[a-zA-Z]"))
    {
        System.out.println("Invalid Input.");
    }
}


这是我到目前为止的代码,但仍在接受数字。

最佳答案

您的循环条件应为:

 while (!familySurname.matches("[a-zA-Z]+")){
     System.out.print("Invalid name - What is your family's surname? ");
     familySurname = keyboard.nextLine();
 }

关于java - 检查用户是否仅在字符串中输入字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20331373/

10-10 13:23