import javax.swing.*; /** * * Class NumericInputParser provides two static methods to parse would-be * numeric input entered in a text field. One method parses any integer, the * other method parses for an integer in a given range. If the input doesn't * parse, the method complains in a GUI dialog. * */ public class NumericInputParser { /** * Call Integer.parseInt to parse the given string-valued number. If it * parses, return the Integer. If the input value does not parse as an * Integer, display an error dialog and return null. *
* The return value of this method is an Integer rather than an int. In * this way, the method can use a null value to indicate that the user * input did not parse as a number. */ public static Integer parse(String number) { try { return Integer.parseInt(number); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Illegal input value", "", JOptionPane.ERROR_MESSAGE); return null; } } /** * Do parse, then ensure that the number is in given start,end range, * inclusive. */ public static Integer parseInRange(String number, int start, int end) { Integer i = parse(number); if (i == null) { return null; } if (i >= start && i <= end) { return i; } else { JOptionPane.showMessageDialog(null, "Illegal input value", "", JOptionPane.ERROR_MESSAGE); return null; } } }