Question:
How do I validate an input ensuring a user enters a number in the range 1-10?
Answer:
See example:
Code:
import java.util.*; public class ReadInt { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int number = 0; while (true) { try { System.out.print("Enter number betwen 1 and 10: "); number = sc.nextInt(); if( number >= 1 && number <= 10){ break; } System.out.println("Out of range."); } catch (InputMismatchException e) { System.out.println("You did not enter a Integer."); sc.nextLine(); // needed to clear buffer } } System.out.println("You entered: " + number); } }
Output:
$ java ReadInt Enter number betwen 1 and 10: 11 Out of range. Enter number betwen 1 and 10: a You did not enter a Integer. Enter number betwen 1 and 10: 12 Out of range. Enter number betwen 1 and 10: 10 You entered: 10