在这里,我有一个简单的 try/catch 语句,用于输入客户名字和姓氏的字符串。但是,如果输入数字或用户输入任何其他非文本字符,我需要抛出异常(因为名称仅包含文本)。问题在于字符串确实接受任何字符而不仅仅是文本。如果用户输入除文本之外的任何内容,我如何才能执行捕获?
public void Customer ()
{
//Variables for Customer method
String firstName;
String lastName;
int customerNumber;
boolean end = false;
/* Reads input from user
* Stores customers first and last name into the variable name
*/
while(end == false)
{
try
{
System.out.println("Enter customers full name" );
firstName = input.nextLine();
System.out.println("Enter customers last name");
lastName = input.nextLine();
end = true;
}
catch (InputMismatchException ime)
{
end = false;
System.out.println("Invalid input. You must enter the customers name. Please try again: ");
input.next();
}
}
}