在具有多种输入类型的扫描仪中正确处理异常

问题描述

如何正确处理扫描仪中的异常?我有不同类型的输入,也不知道如何避免,例如,InputMisMatchException不使用try catch块且不结束程序。 许多输入很多的方法。如何解决此问题并获得清晰的代码?我还在学习,并且是新手。有什么想法可以缩短我的代码吗?这种方法似乎很广泛。我没有重构的经验。 例如我的addPerson方法

  private static void addPerson(Scanner scanner) {
        System.out.println("name:");
        String name = scanner.next();

        System.out.println("surname:");
        String surname = scanner.next();

        System.out.println("age:");
        int age = scanner.nextInt();

        System.out.println("height (in CM):");
        int height = scanner.nextInt();

        System.out.println("weight:");
        double weight = scanner.nextDouble();

        System.out.println("ADDRESS - city:");
        String city = scanner.next();

        System.out.println("ADDRESS - zipCode:");
        String zipCode = scanner.next();

        System.out.println("ADDRESS - street:");
        String street = scanner.next();

        System.out.println("ADDRESS - home number:");
        int homeNumber = scanner.nextInt();

        Person person = new Person();
        person.setName(name);
        person.setSurname(surname);
        person.setAge(age);
        person.setWeight(weight);
        person.setHeight(height);
        Address address = new Address(city,zipCode,street,homeNumber);

        person.setAddress(address);
        personService.add(person);
        System.out.println("Person added to the base with id: " + person.getId());

    }

解决方法

您可以在方法中添加throws关键字

public static void addPerson(Scanner scanner) thorws InputMismatchException {
// your code
}

或者您可以添加try-catch块,但这不会结束您的程序。

private static void addPerson(Scanner scanner) {
   try{
        System.out.println("name:");
        String name = scanner.next();

        System.out.println("surname:");
        String surname = scanner.next();

        System.out.println("age:");
        int age = scanner.nextInt();

        System.out.println("height (in CM):");
        int height = scanner.nextInt();

        System.out.println("weight:");
        double weight = scanner.nextDouble();

        System.out.println("ADDRESS - city:");
        String city = scanner.next();

        System.out.println("ADDRESS - zipCode:");
        String zipCode = scanner.next();

        System.out.println("ADDRESS - street:");
        String street = scanner.next();

        System.out.println("ADDRESS - home number:");
        int homeNumber = scanner.nextInt();
   }
   catch(InputMismatchException inputMismatchException){
      // you can debug,see what caused issue by adding the code below.
      inputMismatchException.printStackTrace();
      // or you can add your code to make it user friendly
      System.out.println("Uh oh! Your input is not the correct type!");
   }

如果您想进一步努力并改善, 您可以为每个输入创建一个while循环,并放置try-catch块,这样,如果用户键入错误并收到异常,则可以让用户重试。

boolean userTypedCorrect = false;
while(userTypedCorrect == false){
   try{
      // your code
      // user typed it correct and didn't get an exception
      // change boolean so while loop exits
      userTpedCorrect = true;
   }
   catch(InputMismatchExecption iOrAnyNameIsFine){
      System.out.println("Try again!");
      // user didn't type it correctly
      // boolean doesn't change so it loops
   }
}

即使您的代码中没有任何错误或错误,如果有可能发生异常,我也会尝试try-catch。 (InputMistMatch是一个很好的例子) 但是,如果某些代码需要异常并且您知道完成编码后不会抛出异常,则可以使用throws。 (例如,当您从.txt文件中读取文件时,它需要IOExecption,但您将始终拥有.txt文件,因此它永远不会引发异常)

提示:

而不是通过方法设置所有内容,
Person person = new Person();
person.setName(name);
person.setSurname(surname);
person.setAge(age);
person.setWeight(weight);
person.setHeight(height);

您可以在Person.java文件中或您的Person类所在的位置创建自己的person构造函数。 (我假设您的Person类中有变量)

public class Person{
   String name; // this.name
   String surname;
   int age;
   // more variables

   public Person(String name,String surname,int age){ // name passed in
      // this.name refers to variable we made at top
      // name refers to name we passed in
      this.name = name;      
      this.surname = surname;
      this.age = age;
   }
}

您结交了一个这样的新人

Person John = new Person("John","Doe",300);

this.variableName = variableName可能会令人困惑,但是一旦您了解它,它就是通常的做法并且很容易。