Search code examples
javainvocationtargetexception

InvocationTargetException while setting values in Java


I have problem with InvocationTargetException. I am setting values of object using scanner and it became to return such strange exception for me. I did read doc and i was searching internet to find solution, but I can't figure out what's wrong. Also don't read println strings, they are in my native language.

public Person SignPerson() { 

    Scanner scanner = new Scanner(System.in);
    System.out.println("Tworzymy twoje konto użytkownika, podaj dane osobowe");
    System.out.println("Podaj swoj pesel");

    String id = setPersonalId();
    Person person = new Person(id);
    System.out.println("Podaj swoje imie");
    person.setFirstName(scanner.nextLine()); // the line taht causes problem (other 
                                                // scanners also throws exceptions)
    System.out.println("Podaj drugie imie");
    //tutaj powinien byc wgrany drugi kod do odczytu imienia
    System.out.println("Podaj nazwisko");
    person.setLastName(scanner.nextLine());
    System.out.println("Podaj nazwisko panienskie matki");
    person.setMotherMaidensName(scanner.nextLine());

    return person;
}

public static String setPersonalId() {
    String id;
    try (
            Scanner scanner2 = new Scanner(System.in);
    ) {
        id = scanner2.next();

        char[] chars = id.toCharArray();

        for (char aChar : chars) {
            if (!(aChar >= '0' && aChar <= '9'))
                throw new InvalidStringException();
        }

        return id;
    } catch (InvalidStringException e) {
        System.out.println("Wprowadziles niepoprawny pesel");
    }

    return null;
}

Solution

  • There might be at least two issues here:

    1. Don't close a Scanner wrapping System.in, as this will also close the underlying stream. (see Close a Scanner linked to System.in)

      To fix this, remove the the creation of the second Scanner from the try-with-resource block, to avoid it getting closed automatically. You may also not create a second scanner, but pass the first one to the method where it will be used.

      String id = setPersonalId(scanner);
      

      and in your setPersonalId:

      public static String setPersonalId(Scanner s) { ...
      
    2. Calling nextLine() after calling next() will also cause problems, explained here: Scanner is skipping nextLine() after using next() or nextFoo()?:

      To fix the second issue, you may simply call nextLine() everytime, instead of next() (or consume the linefeed as shown in the link):

      id = s.nextLine();