Java Notes

Dialog Box: Input Range Method

This utility method shows how to read in a loop until a number in a satisfactory range is entered.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
    //=========================================================== getInt
    // Prompts for an integer in a range.
    // Doesn't handle null (CANCEL) or bad input.
    private static int getInt(String prompt, int min, int max) {
        int result;
        do {
            String strVal = JOptionPane.showInputDialog(null, prompt);
            result = Integer.parseInt(strVal);
            if (result < min || result > max) {
                JOptionPane.showMessageDialog(null,
                 "ERROR: Input must be between " + min + " and " + max);
            }
        } while (result < min || result > max);
        
        return result;
    }