import java.util.Scanner; class Example1 { Scanner s; public Example1() { // create a new scanner that reads from the keyboard s = new Scanner(System.in); } public int promptUserForNum() { // while we don't have an integer, ask the user to give us one while(true) { // prompt the user System.out.print("Please enter a number: "); try { // use Scanner to read the input; // might throw an exception! int x = s.nextInt(); // we got a valid number; break out of this loop and return it return x; } catch (Exception e) { System.out.println("Not an integer! Try again!"); // we have to 'clear' the Scanner; we do this by // reading whatever string it was given, then // discard that string. s.next(); } } // program never reaches this point } public static void main(String[] args) { // initialize our class, which has a Scanner in it Example1 e = new Example1(); // read number int num = e.promptUserForNum(); // tell the user what we got System.out.println("We got: " + num); } }