Domanda

Dont know how to implement the mismatch exception. How do i type a letter when it supposed to be an int and not have the program crash?

try { 
  System.out.print("Enter graduation year : ");
  year = response.nextInt();
} catch (InputMismatchException ex) {
  while (year < 1920 || year > 2010) {
  System.out.print("invalid value. Enter a year between 1920 and 2010 : " );
  year = response.nextInt();
}

Nessuna soluzione corretta

Altri suggerimenti

No, you don't want to get your input in the catch block, but rather want to warn the user of bad input in that block. Instead, set a boolean in the try block after the scanner's nextInt(). Surround the whole thing in a while loop, and only exit the while loop when the boolean has been successfully set.

Pseudocode:

initialize boolean variable, inputStillBad to true. 
while inputStillBad
  try block
    prompt user for input
    get input from scanner
    if this line was reached, then scanner succeeded
    check if year is within bounds, and if so:
      set inputStillBad to false.
    else:
      warn user that the year was out of range
  catch your exception here
    warn the user that they entered non-numeric input
end while loop

You can check if the user has entered an Int as follows :

if(response.hasNextInt())
{
 year = response.nextInt();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top