I am a beginner to Java and am just starting to use the JOptionPane. I have been playing with the for loop and have hit a snag. I want to accumulate a dollar amount in a for loop and when the user types in a 'q', exit the loop and then display the accumulated total. The code seems to run fine except after typing a q, I get an exception error. How should it be done?
To compare the input with the letter 'q', you need to use String.equals() or String.equalsIgnoreCase(), not "==". The equals operator (==) will only return true if you are comparing two references of the same object, not two objects with the same value(s).
Your program gets an exception because, since it does not detect that the q ends the loop, it then tries to parse it as a double.
One thing about Java error messages it is good to learn -- they almost always tell you what's wrong and where to look for it -- I get "Exception in thread "main" java.lang.NumberFormatException: For input string: "q". It's a very clear indication of where the exception came from, though it would not necessarily have told someone who hasn't made the mistake before about the equal operator and strings.
Avoid System.exit(). Where you have it, it is unecessary, since the JVM will close after that line anyway. System.exit() has its uses, but it can be a bit vicious. For example, if you have one thread which you have finished with, and another writing to a file, calling System.exit() on the first thread will terminate the whole JVM, and you may find your file is never closed correctly, or the data are not recorded completely.
Joined: Oct 13, 2005
A lot of people show you how to use double arithmetic for money, but you ought not to. This post tells you what you ought to do, but you will have to do a bit more work about how many figures you are recording. You can use new BigDecimal(input); but you willl suffer the same exception if you pass q.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com