Java examples for Language Basics:while
Get Integer method that uses a while loop to avoid the exception.
import java.util.*; public class GetInteger2 { static Scanner sc = new Scanner(System.in); public static void main(String[] args) {/* w w w.jav a2s .co m*/ System.out.print("Enter an integer: "); int i = GetInteger(); System.out.println("You entered " + i); } public static int GetInteger() { while (!sc.hasNextInt()) { sc.nextLine(); System.out.print("That's not " + "an integer. Try again: "); } return sc.nextInt(); } }