【问题标题】:Handling exceptions properly in scanner with many types of input在具有多种输入类型的扫描仪中正确处理异常
【发布时间】:2020-09-04 10:48:54
【问题描述】:

如何正确处理扫描仪中的异常?我有不同类型的输入,不知道如何避免,例如 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());

    }

【问题讨论】:

    标签: java exception try-catch java.util.scanner


    【解决方案1】:

    您可以在方法中添加 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 类中有变量)

    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 可能会令人困惑,但这是一种常见的做法,一旦你理解了它就很容易。

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2015-05-07
      相关资源
      最近更新 更多