import java.util.Scanner; /** Error4.java - More error checking of user input. A more serious kind * of input error is when the type of input is unexpected. For example, * we ask for a number and we get a string. */ public class Error4 { public static void main(String [] args) { Scanner kbd = new Scanner(System.in); // We need to declare the input variable before the loop and try/catch. int n = 0; boolean needInput = true; while (needInput) { System.out.print("Please enter an integer: "); // If the user enters a string, we get a NumberFormatException. // It's good to put as little code in the try/catch as possible. // Only put the risky code in the try part. try { n = Integer.parseInt(kbd.nextLine()); } catch (NumberFormatException e) { System.out.println("Sorry, I don't understand. Try again."); continue; } // If we get this far, the input is okay. needInput = false; } System.out.println("You entered " + n); } }