In Java Swing, Prompt for cost in cents and do validations

/*
  Display the change only if a valid price is entered (no less than 25 cents,
  no more than 100 cents, and an integer multiple of 5 cents). Otherwise,
  display separate msg messages for any of the following invalid inputs: a
  cost under 25 cents, a cost that is not an integer multiple of 5, and a cost
  that is more than a dollar.
*/

import javax.swing.JOptionPane;

public class Test{
  public static void main(String[]args){
    final byte MIN = 25, MAX = 100, MOD = 5;
    final String prompt = String.format("Enter cost between %d and %d", MIN, MAX);
    String input = JOptionPane.showInputDialog(null, prompt);
    String msg = null;
    try{
      int cost = Integer.parseInt(input, 10);
      if (MIN > cost) {
        msg = String.format("Cost cannot be less than %d cents", MIN);
      } else if (MAX < cost) {
        msg = String.format("Cost cannot be more than %d cents", MAX);
      } else if (0 != cost%MOD) {
        msg = String.format("Cost has to be multiple of %d", MOD);
      }
    }catch(NumberFormatException ex){
      msg = "Not a valid cost!";
    }
    int icon = JOptionPane.INFORMATION_MESSAGE;
    String title = "Information";
    if (null != msg) {
      icon = JOptionPane.ERROR_MESSAGE;
      title = "Error";
    } else {
      msg = "All good!";
    }
    JOptionPane.showMessageDialog(null, msg, title, icon);
  }
}

Comments

Popular posts from this blog