Handling exceptions properly in scanner with many types of input

Viewed 531

How properly handle exceptions in scanner? I have different types of inputs and no idea how avoid, for example InputMisMatchException without using try catch block and without ending program. Many methods with many inputs. How can I resolve this problem and have a clean code? I'm still learning and I'm beginner. Any ideas to short my code? This method seems to be to extensive. I have no experience with refactoring. For example my addPerson method:

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

    }
1 Answers

You can add throws keyword to your method

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

OR you can add try-catch block and this won't end your program.

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

If you want to go the extra mile and improve, You can create a while-loop for each input and put try-catch block so if the user types something wrong and you get an exception, you have the user try again.

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
   }
}

I would go with try-catch if there's a chance of an exception even you don't have any errors or bugs in your code. (InputMistMatch is a good example) But if some code requires exception and you KNOW it won't throw an exception when finished coding, you can just use throws. (EX. when you're reading from a .txt file it requires IOExecption but you'll always have the .txt file so it'll never throw an exception)

Tip: Instead of setting everything through methods,

Person person = new Person();
person.setName(name);
person.setSurname(surname);
person.setAge(age);
person.setWeight(weight);
person.setHeight(height);

you can create your own person constructor in Person.java file or where your Person class is. (I assume you have variables in your Person class)

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;
   }
}

And you make a new person like this

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

this.variableName = variableName might be confusing but it's common practice and easy once you understand.

Related