So i have these lines:

try {
   extra = Double.parseDouble(igu.txfExtra.getText());
} catch (NumberFormatException e1) {
   System.out.print("Error");               
}

It collects a double from a JTextField called txfExtra.

How can I say in the System.out.print if the error was made by introducing letters in the label for example? I mean, if the error was due to the "extra" collecting a String, show that the error was due to a string.

Also an extra question, how can i make "extra" to take values with BOTH "." and "," because due to localization it either takes for example "10.923" or either "10,923" i want it to accept both types of format when parsing the double.

有帮助吗?

解决方案

In order to satisfy both requirements, you would need something else than Double.parseDouble(). For one, it will use the current locale; also, its error message won't be as detailed as you want to be.

A solution would be to go through a regex to parse the input string, and only if the regex passes, parse using a NumberFormat:

private static final Pattern NUMPATTERN = Pattern.compile("\\d+([.,])\\d+");

// ...

// Supposes a custom MyException class
public double doParseDouble(final String input)
    throws MyException
{
    final Matcher m = NUMPATTERN.matcher(input);
    if (!m.matches())
        throw new MyException("Non number characters in input");

    final String separator = m.group(1);
    final Locale locale = ".".equals(separator)
        ? Locale.US : Locale.FRENCH;

    final NumberFormat fmt = NumberFormat.getInstance(locale);

    try {
        return fmt.parse(input).doubleValue();
    } catch (NumberFormatException e) {
        throw new MyException(e);
    }
}

This is only sample code and lacks a LOT of features:

  • restricts to only a subset of valid doubles (.1 will not be accepted for instance; or 1.4e-3);
  • does not deal with overflows/underflows;
  • others.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top