This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes divide by 0 exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "divide by 0 exception" Watch "divide by 0 exception" New topic
Author

divide by 0 exception

Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

i wrote a calculator program like the windows one(well sort of). anyway i had to add a lot of if's to catch bad input that would result in a runtime exception. now i think i am down to only having the divide by 0 one left. if you can find others please let me know. anyway i cant just say if text.equals("0") because it could also be "0.0" ...hmm i could OR them hmmm..

i plan to refactor it when i shake all the bugs out im just wondering if any of you can find some more exception throwing code. or code that doesn't perform correctly.


SCJP
Visit my download page
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
I would suggest you refactor your Listener class, too. That single method is far too long. Individual Listeners associated with each button would be better. You could have a NumberListener class with 0, 1, 2 etc., as fields for the individual instances.

What about creating a BigDecimal instance from the text, testing its difference from ZERO with the compareTo method and throwing the Exception if the difference is 0?
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

i like the single switch statement to handle all action events. it is thanks to java7 that i can do it so easily. i forgot to mention you need java7 to compile or run this.

i was thinking along the same lines. i was going to use Double.parseDouble() to change it to a number and then compare. if they are trying to divide by zero i will use JOptionPane to alert them.....BigDecimal and ZERO look better

i am going to add two lines of code to my original post(rather than repost it all) the case "C" block
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: divide by 0 exception