Java examples for Object Oriented Design:Method
Uses a method to get a valid integer from the user with catch block that catches the error and forces the loop to repeat.
import java.util.*; public class GetInteger { static Scanner sc = new Scanner(System.in); public static void main(String[] args) {/*from w w w .j a va 2 s . com*/ System.out.print("Enter an integer: "); int i = GetInteger(); System.out.println("You entered " + i); } public static int GetInteger() { while (true) { try { return sc.nextInt(); } catch (InputMismatchException e) { sc.next(); System.out.print("That's not " + "an integer. Try again: "); } } } }