brainfrz

Untitled

Oct 11th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class PromptInRange
  4. {
  5.     public static int promptIntInRange( String prompt, int min, int max, String minError,
  6.         String maxError )
  7.     {
  8.         Scanner user_input = new Scanner(System.in);
  9.         int number;
  10.  
  11.         do
  12.         {
  13.             if (min == Integer.MIN_VALUE && max == Integer.MAX_VALUE)
  14.             {
  15.                 System.out.print(prompt + ": ");
  16.             }
  17.             else if (min == Integer.MIN_VALUE)
  18.             {
  19.                 System.out.print(prompt + " (less than " + max + "): ");
  20.             }
  21.             else if (max == Integer.MAX_VALUE)
  22.             {
  23.                 System.out.print(prompt + " (greater than " + min + "): ");
  24.             }
  25.             else
  26.             {
  27.                 System.out.print(prompt + " (between " + min + " and " + max + "): ");
  28.             }
  29.  
  30.             try {
  31.                 number = Integer.parseInt(user_input.next());
  32.  
  33.                 if (number < min)
  34.                 {
  35.                     System.out.print(minError + " ");
  36.                 }
  37.                 else if (number > max)
  38.                 {
  39.                     System.out.print(maxError + " ");
  40.                 }
  41.             } catch (NumberFormatException e) {
  42.                 number = min - 1;
  43.                 System.out.print("Input wasn't an integer. ");
  44.             }
  45.         } while (number < min || number > max);
  46.  
  47.         return number;
  48.     }
  49.  
  50.     public static int promptIntInRange( int min, int max, String minError, String maxError )
  51.     {
  52.         return promptIntInRange("Please enter an integer", min, max, minError, maxError);
  53.     }
  54.  
  55.     public static int promptIntInRange( int min, int max, String error )
  56.     {
  57.         return promptIntInRange(min, max, error, error);
  58.     }
  59.  
  60.     public static int promptIntInRange( int min, int max )
  61.     {
  62.         return promptIntInRange(min, max, "That's out of range.");
  63.     }
  64.  
  65.  
  66.     public static int promptWholeNumber( String error )
  67.     {
  68.         return promptIntInRange(0, Integer.MAX_VALUE, error);
  69.     }
  70.    
  71.     public static int promptWholeNumber()
  72.     {
  73.         return promptWholeNumber("That's a negative number.");
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment