Problem causing exception InputMismatchException

0

I have a problem after I skipped the exception about the edat attribute. The problem is that when I miss the error and capture it instead of asking me the next question that would be the dni I jump directly to ask the population, that is, skip the% of dni .

I leave the code:

System.out.printf("Introdueix la edat ");
try {
    edat = pregunta.nextInt();
} catch (InputMismatchException m) {
    System.err.println("Exception: " + m);
}
System.out.printf("Introdueix el dni ");
dni = pregunta.next();
System.out.printf("Introdueix la provincia ");
provincia = pregunta.next();
    
asked by Javi Palacios 15.12.2016 в 17:47
source

1 answer

0

The problem is that the nextInt() method does not consume a new line because it is converted to int so it can not have a new line .

It would be best to use nextLine() and make a cast to int with that this "weird" or unexpected behavior does not occur:

System.out.print("Introdueix la edat ");

try {
    edat = Integer.parseInt(pregunta.nextLine());

} catch (NumberFormatException e) {
    e.printStackTrace();                
}

System.out.print("Introdueix la provincia ");
provincia = pregunta.nextLine();

System.out.print("Introdueix el dni ");
dni = pregunta.nextLine();
    
answered by 15.12.2016 в 18:37