Java 当一行中需要多个输入时,用户输入的异常处理
我正在开发一个程序,用户可以在其中添加人员和车辆。程序按照scholl作业的要求运行,但是如果用户输入无效语句,我希望它能够更好地处理异常 我有这个,它的工作原理是将用户放回程序的菜单中,这样程序就不会崩溃,但我不希望用户重新开始添加对象的过程,而是从发生错误的地方重试 代码如下:Java 当一行中需要多个输入时,用户输入的异常处理,java,exception-handling,user-input,Java,Exception Handling,User Input,我正在开发一个程序,用户可以在其中添加人员和车辆。程序按照scholl作业的要求运行,但是如果用户输入无效语句,我希望它能够更好地处理异常 我有这个,它的工作原理是将用户放回程序的菜单中,这样程序就不会崩溃,但我不希望用户重新开始添加对象的过程,而是从发生错误的地方重试 代码如下: // adds person to registry public void addPerson(){ try { System.out.println("Name of person
// 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.");
}
}
}
注意:您将
nextLine
和next
混用表示您没有正确使用扫描仪;您应该只使用其中一个或仅使用另一个。如果您希望向用户请求可以包含空格的输入,请将扫描仪配置为在换行符上拆分输入,而不是“任何空格”。创建字符串后立即调用sc.usedimiter(“\r?\n”)
,要检索字符串,只需调用next()
。这将检索整行。将请求一条信息的每个部分提取到自己的方法中,该方法请求信息,验证信息,然后再次请求,直到信息正确为止。您的addPerson()方法可以归结为personList.add(newperson(askName()、askAge()、askCity())代码>。