brilliant_moves

IntegerInput.java

Mar 4th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.19 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.InputMismatchException;
  3.  
  4. public class IntegerInput {
  5.  
  6.     /**
  7.     *   Program:    IntegerInput.java
  8.     *   Purpose:    Validating user input
  9.     *   Creator:    Chris Clarke
  10.     *   Created:    04.03.2014
  11.     */
  12.  
  13.     private static final int MIN = 1;
  14.     private static final int MAX = 21;
  15.  
  16.     public static void main(String[] args) {
  17.  
  18.         // create scanner for keyboard input
  19.         Scanner keybd = new Scanner(System.in);
  20.         int n;
  21.  
  22.         // start do..while loop
  23.         do {
  24.             // prompt user
  25.             System.out.print("Enter integer number between "+MIN+" and "+MAX+": ");
  26.  
  27.             try {
  28.                 // get an integer
  29.                 n = keybd.nextInt();
  30.             } catch (InputMismatchException e) {
  31.                 // display error message
  32.                 System.out.println("That\'s not an integer!");
  33.                 // quit program
  34.                 return;
  35.             } // end try/catch
  36.  
  37.             if (n<MIN) {
  38.                 System.out.println("Number too low! Must be "+MIN+" or above.");
  39.             } else if (n>MAX) {
  40.                 System.out.println("Number too high! Must be "+MAX+" or below.");
  41.             } // end if
  42.         // ...while outside range
  43.         } while (n<MIN || n>MAX);
  44.  
  45.         // confirm number entered by user
  46.         System.out.println("Thank you.  You entered "+n+".");
  47.  
  48.     } // end main()
  49.  
  50. } // end class IntegerInput
Advertisement
Add Comment
Please, Sign In to add comment