本质上,这个程序的想法是测试用户输入并抛出我在输入无效数据时创建的异常。例如:名称不能为空,必须全部为字母字符(无特殊或数字)。我已将其嵌入到一个 do-while 循环中,只要不输入 q 退出该循环就会继续。我正在通过扫描线读取用户输入,然后将输入的字符串发送到验证它是否符合标准的函数。如果没有,则该函数将引发我的自定义异常。一切正常,除了抛出异常时,它仍然采用该字符串并将其放入新的 Person 对象中。
如何向用户抛出异常,但要求他们重新输入姓名或年龄,直到输入正确?
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter person info or q to quit.");
System.out.print("Please enter the name of this person:");
String name = input.nextLine();
if(name.equalsIgnoreCase("q"))
{
break;
}
try{
isName(name);
}catch (InvalidNameException n){
System.out.println(n);
}
System.out.print("Please enter an age for this person:");
String age = input.nextLine();
try{
isValidAge(age);
}catch(InvalidAgeException a){
System.out.println(a);
}
public static void isName(String name) throws InvalidNameException
{
if(name.isEmpty())
{
throw new InvalidNameException("You did not enter a name.");
}
String[] namez = name.split(" ");
for(int i=0;i<namez.length;i++)
{
char[] charz = namez[i].toCharArray();
for (char n : charz)
{
if(!Character.isLetter(n))
{
throw new InvalidNameException("You have entered an invalid name.");
}
}
}
}