import java.util.Scanner; class Example2 { Scanner s; public Example2() { // 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: "); // did the user enter an integer? if (s.hasNextInt()) { // return the number return s.nextInt(); } else { 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 Example2 e = new Example2(); // read number int num = e.promptUserForNum(); // tell the user what we got System.out.println("We got: " + num); } }