简体   繁体   中英

How to catch incorrect input using JOptionPane?

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

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 (ie 3.567)) display an error message and stop the program execution.
  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);

The first part of checking whether the input is of the right format is as you've done: use Double.parseDouble() to convert the String to a double . When you do this, you can use a try / catch block to catch a NumberFormatException , which will occur if the input couldn't be turned into a floating point number at all.

But you've also been asked to check that you don't have more than two digits after the decimal point. This is a little trickier. I would suggest that you use String.indexOf() to find the decimal point in the input string, and then check that there aren't more than two characters (by which I include digits) after that point.

There are other options, but they are probably trickier if you're not familiar with them:

  1. Use a regular expression.
  2. Convert to a BigDecimal , and then check that if you round to two decimal places, you end up with the same BigDecimal that you started with.

Note: do not try this second approach with a double . A double can't always represent decimal numbers exactly, so rounding to two decimal places and checking it's unchanged might give you false positives (seeming errors where there aren't errors).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM