File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Exiting for loop using JOptionPane Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exiting for loop using JOptionPane" Watch "Exiting for loop using JOptionPane" New topic

Exiting for loop using JOptionPane

Billy White

Joined: Nov 28, 2010
Posts: 4
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?

Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
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.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46412
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.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46412
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 agree. Here's the link:
subject: Exiting for loop using JOptionPane
It's not a secret anymore!