// GetNumber.java // Shows a way to get a number from the user, while verifying // that the user enters a number within a specified range. // cmc, 10/21/08 import java.util.Scanner; // for user input public class GetNumber { public static void main(String[] args) { // define the allowable range for input values final int MIN = 1, MAX = 10; // create Scanner object associated with standard input Scanner input = new Scanner(System.in); // begin a loop that will make sure user enters a proper value int value = MIN - 1; while (value < MIN || value > MAX) { // prompt the user to enter a value in allowable range System.out.printf("Enter integer between %d and %d:%n", MIN, MAX); // verify the user is entering an int if ( input.hasNextInt() ) { // true means an int has been entered, so read it as int value = input.nextInt(); // print an error message if the value is out of range if (value < MIN || value > MAX) System.out.println("value is out of range: " + value); } else { // user did not enter an int // must read the non-int as a String to get it out of the way, // and might as well print it out with an error message String junk = input.next(); System.out.println("input is not an int: " + junk); } } // made it out of the while loop, so user entered a proper value System.out.println("Good job! You entered: " + value); } }