Question

I'm learning java and I'm trying to make a very simple application that does conversion of currency. You enter a rate, a direction (e.g : from euro to dollars or reverse) and an amount. the numbers valid non negative numbers.

So far I managed to make it so that the number can't be negative; now I need to throw an error if it's not a number. I have following code:

public void setKoers(double koers) 
            throws NegativeValueException, NumberFormatException{
    if (koers > 0 ) {
            this.koers=koers;
        } else {
            throw new NegativeValueException("negative number");
        }
}

and my main looks like

    try   {
            cal.setKoers( Double.parseDouble(args[0])); 

          } catch(NegativeValueException e) {
             System.out.println(e.getMessage());
          } catch (NumberFormatException e) {
             System.out.println( e.getMessage());
          }

So how can I check if koers is a number or not. I know I could put try and catch the error in my code, but I think this would go against the logic of where and how to deal with errors: in my main function I should catch any NumberFormatException

Was it helpful?

Solution

You do not need the NumberFormatException since Double.parseDouble() takes care of it for you. If it is not a proper number (in this case a Double) than the parseDouble() method will throw a NumberFormatException for you.

Here's how I would write it: (just take out the NumberFormatException)

public void setKoers(double koers) throws NegativeValueException {
    if (koers > 0 ) {
            this.koers=koers;
        } else {
            throw new NegativeValueException("negative number");
        }
}

try{
    cal.setKoers( Double.parseDouble(args[0]));

    } catch(NegativeValueException e) {
        System.out.println(e.getMessage());
    } catch (NumberFormatException e) {
        System.out.println( e.getMessage());
    }

OTHER TIPS

You will probably want to validate your input when the user tells the program to accept and process the input. In this portion of the code, you would convert the String to a number by parsing the input within a try/catch block, and then if an exception is encountered, notify the user of the error, prevent further processing, and perhaps clear any offending entry fields if present.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top