当需要一行中的多个输入时,使用用户输入进行异常处理



我正在开发一个程序,用户可以在其中添加人员和车辆。该程序按照 scholl 赋值的要求运行,但是我希望它在用户输入无效语句时通过处理异常来更好地工作。

我有这个,它的工作原理是让用户回到程序的菜单中,这样程序就不会崩溃,但我不希望用户必须重新开始添加对象的过程,而是从发生错误的 excact 位置重试。

这是代码:

// 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();
}
}

如果用户在"输入年龄:"问题中键入除整数以外的任何内容,则会发生此错误。

我有另一种添加车辆的方法,它需要更多的用户输入,特别是在这种方法中,如果用户必须重新开始,那将是相当糟糕的。

如何解决?

创建一个帮助程序方法:

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.");
}
}
}

注意:你混合使用nextLinenext<随便什么>表明你没有正确使用扫描仪;你应该只使用一个或只使用另一个。如果您希望要求用户输入可以包含空格的输入,请将扫描程序配置为在换行符上拆分输入,而不是"任何空格"。通过在创建字符串后立即调用sc.useDelimiter("r?n")来执行此操作,要检索字符串,只需调用next()即可。这将检索整行。

最新更新