1

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

1
  • 2
    I'm confused at what you're asking. Double.parseDouble(args[0]) is what can throw a NumberFormatException. Not sure why your setKoers method has a throws clause for that. Commented Dec 25, 2011 at 23:26

2 Answers 2

2

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()); } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

I might have missed something, but as far as I can tell, Swing was never mentioned, nor a GUI in general.
@Corbin: you are correct, and I am wrong. Thanks for the sharp eyes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.