Search code examples
javajoptionpane

how to stop the program when the user inputs the wrong type of data?


Hey I have to ask the user for a purchase amount using JOptionPane and if they input more than two decimal places, nothing, characters, or more than one decimal point the program has to show an error message and stop.

How would I do this?

I don't want someone to write the program for me just a link that explains how I would do it

  String PurchaseAmount = JOptionPane.showInputDialog(null, String.format("What is your purchase amount?")); 
  double PurchaseTotal = Double.parseDouble(PurchaseAmount);

  String PaymentAmount = JOptionPane.showInputDialog(null, "What is the payment amount?");
  double PaymentGiven = Double.parseDouble(PaymentAmount);

if the user inputs "12.526" or " " or "1.3.25" or "abc" I want the program to show an error message and stop.

Since this appears to be a confusing question or I'm asking it incorrectly these are my teachers directions exactly:

  1. The program must ask the user to input the purchase amount, using JOptionPane.showInputDialog
  2. The program must ask the user to input the payment amount, using JOptionPane.showInputDialog
  3. The program must catch incorrect input (empty, null, characters, more than one decimal point, more than two decimal places (i.e. 3.567)) display an error message and stop the program execution.

Solution

  • You'll want to write a method to validate the input. This can be done in steps:

    First split the input on "."

    • if length of the resulting array >2, return false
    • if length of the second string in the array >2, return false
    • if the first string does not parse to a double, return false
    • etc, etc, go through all of the conditions that make this true
    • if it passes all the tests, return true

    (Alternatively, you can use a regular expression instead of a series of tests. This is probably a better solution, but I figure if you use one, you're going to have to maintain it, so you'll have to start by learning to write it.)

    When you get back the validation, if the entry passes, parse it and get on with the next step. If false, exit in some sane way (preferably not by System.exit() - you'd like to be able to terminate in a graceful fashion)