import java.util.Scanner; import java.util.InputMismatchException; /** * CS151 Fall 2007 in class exericse (11/30).
* Keeps trying to read a user entered input from the terminal until a valid * integer is entered. * * @author Scott Russell * @version 11/30/2007 */ public class GetInt { public static void main(String[] args) { int number = 0; // used to decide when we are finished boolean validNumber = false; Scanner console = new Scanner(System.in); // keep asking for a integer, try to read, catch an error and repeat // until valid integer entered while (!validNumber) { try { System.out.print("Please enter an integer (e.g. 6, -5): "); number = console.nextInt(); validNumber = true; System.out.println("You entered " + number); } catch(InputMismatchException exception) { // throw away the bad input so we can read the new input console.nextLine(); } } } }