Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.InputMismatchException;
- public class IntegerInput {
- /**
- * Program: IntegerInput.java
- * Purpose: Validating user input
- * Creator: Chris Clarke
- * Created: 04.03.2014
- */
- private static final int MIN = 1;
- private static final int MAX = 21;
- public static void main(String[] args) {
- // create scanner for keyboard input
- Scanner keybd = new Scanner(System.in);
- int n;
- // start do..while loop
- do {
- // prompt user
- System.out.print("Enter integer number between "+MIN+" and "+MAX+": ");
- try {
- // get an integer
- n = keybd.nextInt();
- } catch (InputMismatchException e) {
- // display error message
- System.out.println("That\'s not an integer!");
- // quit program
- return;
- } // end try/catch
- if (n<MIN) {
- System.out.println("Number too low! Must be "+MIN+" or above.");
- } else if (n>MAX) {
- System.out.println("Number too high! Must be "+MAX+" or below.");
- } // end if
- // ...while outside range
- } while (n<MIN || n>MAX);
- // confirm number entered by user
- System.out.println("Thank you. You entered "+n+".");
- } // end main()
- } // end class IntegerInput
Advertisement
Add Comment
Please, Sign In to add comment