我正在开发一个程序,用户可以在其中添加人员和车辆。该程序可以满足scholl分配的要求,但是我希望它可以通过在用户输入无效语句时处理异常来更好地工作。
我有这个功能,它的工作原理是让用户回到程序菜单中,因此程序不会崩溃,但是我不希望用户必须重新启动添加对象的过程,而是从发生错误的确切位置重试。
代码如下:
// adds person to registry
public void addPerson(){
try {
System.out.println("Name of person: ");
String name = Main.sc.nextLine();
System.out.println("Age of person: ");
int age = Main.sc.nextInt();
Main.sc.nextLine();
System.out.println("City of residence: ");
String city = Main.sc.nextLine();
Person person = new Person(name, age, city);
personList.add(person);
}catch (InputMismatchException e){
System.out.println("Not a valid input. Try again");
Main.sc.nextLine();
}
}
如果用户在“输入年龄:”问题中输入除整数以外的任何内容,则会发生错误。
我还有另一种添加车辆的方法,该方法需要更多的用户输入,尤其是在该方法中,如果用户必须重新开始,那将是非常糟糕的事情。
该如何解决?
答案 0 :(得分:0)
制定帮助方法:
public int askInt(String prompt) {
while (true) {
System.out.println(prompt);
try {
return Main.sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter an integer number.");
}
}
}
NB:nextLine
和next
<任何内容>的混合使用表明您没有正确使用扫描仪;您应该只使用一个或另一个。如果您想询问用户可能包含空格的输入,请将扫描仪配置为在换行符上分割输入,而不是“任何空白”。通过在创建之后立即调用sc.useDelimiter("\r?\n")
来执行此操作,并检索一个字符串,只需调用next()
。这将检索整行。