[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

ArithmeticException

Posted on 2005-05-02
12
Medium Priority
?
258 Views
Last Modified: 2010-03-31
The code bellow has a problem, which is when I try to divide 5 / 0, the catch(ArithmeticException a) is not invoked. How do I solve the problem?.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Arithmetic extends JFrame implements ActionListener
{
       JLabel lb1,lb2,lb3,lb4;
       JTextField tf1,tf2;
       JButton pl,mi,di,mu;
      
       public Arithmetic()
       {
             Container cp = getContentPane();
             
             setTitle("Arithmetic GUI");
             setSize(300,200);
            
           cp.setLayout(new FlowLayout());
          
           Panel p1 = new Panel(new GridLayout(0,1,0,8));
           lb1 = new JLabel("Number 1");
           lb2 = new JLabel("Number 2");
           lb3 = new JLabel("Answer");
           p1.add(lb1);
           p1.add(lb2);
           p1.add(lb3);
          
           Panel p2 = new Panel(new GridLayout(0,1,0,8));
           tf1 = new JTextField(15);
           tf2 = new JTextField(15);
           lb4 = new JLabel("");
           p2.add(tf1);
           p2.add(tf2);
           p2.add(lb4);
      
           Panel p3 = new Panel(new GridLayout(0,1,0,8));
           pl = new JButton("+");
           mi = new JButton("-");
           di = new JButton("/");
           mu = new JButton("*");
           p3.add(pl);
           p3.add(mi);
           p3.add(di);
           p3.add(mu);
          
           pl.addActionListener(this);
           mi.addActionListener(this);
           di.addActionListener(this);
           mu.addActionListener(this);
          
           cp.add(p1);
           cp.add(p2);
           cp.add(p3);
       }
      
       public static void main(String[] args)
       {
           JFrame f = new Arithmetic();
           f.setVisible(true);      
       }
      
       public void actionPerformed(ActionEvent ae)
       {
              try
              {
                    double d1 = Double.parseDouble(tf1.getText().trim());
                    double d2 = Double.parseDouble(tf2.getText().trim());
             
                    if(ae.getSource()==pl)
                    {
                        lb4.setText(Double.toString(d1+d2));      
                    }
             
                    if(ae.getSource()==mi)
                    {
                           lb4.setText(Double.toString(d1-d2));
                    }
             
                    if(ae.getSource()==di)
                    {
                        lb4.setText(Double.toString(d1/d2));
                    }
             
                    if(ae.getSource()==mu)
                    {
                           lb4.setText(Double.toString(d1*d2));
                    }
              }
              catch(NumberFormatException nfe)
              {
                    JOptionPane.showMessageDialog(this,"You must enter number in both fields","Error",JOptionPane.ERROR_MESSAGE);
              }
              catch(ArithmeticException a)
              {
                    lb4.setText("Division by zero NOT allowed!");
              }
       }
}

Your help is kindly appreciated.

Regards

Eugene
0
Comment
Question by:eugene007
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 13911895
You're not performing an arithmetic - just parsing Strings
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13911900
an = any
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13911944
Replace:

>>lb4.setText(Double.toString(d1/d2));

by

lb4.setText(Double.toString(d1/d2));
double result = d1 / d2;
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 15

Accepted Solution

by:
JakobA earned 200 total points
ID: 13912116
when using floatingpoint variables division by 0 is not an error.
if yiu look in the predefined class double you will find (at the top)

public final
class Double extends Number {
    /**
     * The positive infinity of type <code>double</code>.
     *
     * @since   JDK1.0
     */
    public static final double POSITIVE_INFINITY = 1.0 / 0.0;

division by 0 gives positiov(or negative) infinity.

This is because floatingpoint numbers are, by definition, not exact values, they are approximate with whatever granularity the representation permit.

So the reason you do not get an exception is that no exception is generated.

regards JakobA
0
 
LVL 15

Expert Comment

by:JakobA
ID: 13912128
If you modify your calculator to work with int's or long's you will get that exception.
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13912146
>> I try to divide 5 / 0, the catch(ArithmeticException a) is not invoked
Devision by zero for non integral values (double, float) will not  throw an Arithmetic exception but rather return a value Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY.
You can replace the values to an integral type (int or long) to get Arithmetic exception
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13912159
Sorry JakobA, not intentional
eugene007, disregard my answer as JakobA already provided it.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13912805
>> when using floatingpoint variables division by 0 is not an error.

Yep. I'm losing concentration - the calculation's being done too ;-)
0
 
LVL 15

Expert Comment

by:JakobA
ID: 13914981
Why    float / 0.0    is not an error.

To explain we must start with integers. The integers consist of a set of discrete values ..., -1, 0, 1, 2, 3, 4, ... each value distinct and exact, and separate from all the others.

Drawing a graph of integers we see that they form a graph that is not continuous

...     .     .     .    .     .     .     .     .     .    .     .     .     .    ...
...   -3   -2   -1    0    1    2    3    4    5    6    7    8    9    ...

each integer correspond to one exact point on that graph

Integers are fine for buying groceries, but when we start building bridges, measuring land and calculating cosines we need something more differentiated, We need to fill the holes in the integer graph abowe.

So we make real numbers. halfway between 0 and 1 we place 0.5, halfvay between 0 and 0.5 we place 0.25, and we formulate that as a rule so that conceptially we can do it forever turning the non continuos interger graph into a continuous real nr graph

...   -+----+----+----+----+----+----+----+----+----+----+----+----+----+-  ...
...  -3.0 -2.0  -1.0  0.0   1.0  2.0   3.0  4.0   5.0   6.0  7.0   8.0  9.0  10.0

For every point on that line there is a real number corresponding to that point. It may take millions of decimals to specify that number, It may even take an infinite nr of decimals (as with PI); but the number is there. every point on the line has a number (conceptually, in the math sense) real numbers are a continuous function, and that is quite valuable.

Now along come computers and we want to put numbers into them.

For integers it is pretty easy, a bitpattern pr integer represent that  and only that integer. There are limits to how many integers we can represent, determined by the nr of bits in the int or long variable. but those integers we chose to represent are represented exactly. When the computer sees the bitpattern assigned to integer 0 it means exactly 0.

But for Reals it is harder the real function is not only infinitely long (from minus infinity to plus infinity) it is also infinitely detailed. between any two points on the line there is an infinity of other (more detailed) real numbers. And in order to map that onto a finite set of bitpatterns we have to compromize.

The compromize is 'floating point' numbers. a fixed size exponent giving the magnitude of the number, a sign bit, and a fixed nr of digit-bits specifying the most significant digits of the number. with that you can build bridges or scyscrapers. if you increase the nr of exponent and digit bits you can even design spaceshuttels and calculate planetary motions. It works, but it is important to realize that it is a compromize.

The graph for floatingpoint numbers look just like the graph for reals:

...   -+----+----+----+----+----+----+----+----+----+----+----+----+----+-  ...
...  -3.0 -2.0 -1.0  0.0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0 10.0  ...

but between any 2 numbers that can be represented with flotingpoint format there is a gaping hole with an infinity of more detailed real numbers that cannot be represented. The function for floatingpoint numbers are NOT continuous.

For math to work we need that continuity, and so we lie. Instead of saying each number represent an exact point on the line we spread it out and say it represent a short piece of line. just long enough to reach the next floatingpoint number that can be represented with the number of exponent-bits and digit-bits we have assigend to our floatingpoint numbers. A floatingpoint number represent all of the real values on that little piece of line and with this lie we have all the benefits of the continuous real number function back, we can divide any number by any number and get a result ( not totally exact maybe, but if it is good enough for building a space shuttle its good enough for me. :-))

And now the bit representation of 0.0 do not really mean zero, it means 'anything from a little less than zero to a little more than zero. It represent an infinite number of real (very small) values and only a single one of those values is actually zero.

So it makes sense to say that when you divide by the value zero you are not really dividing by zero, but just by a humungously small number. And the result of that is a number so large that the exponent part of our floatingpont representation do not have enough bits for its magnitude. That is what the special infinity bitpattern mean in floatingpoint. the number got so big it cannot be represented.

Does this make any sense ?

regards JakobA
0
 
LVL 4

Expert Comment

by:delphi3
ID: 13923824
Hi eugene007,

My contribution to this Q: a bit more about the math at:
http://mathforum.org/dr.math/faq/faq.divideby0.html

and this programming revision for the (ActionEvent ae) below

Delphi3

 

public void actionPerformed(ActionEvent ae)
  {
    try
    {
      double d1 = Double.parseDouble(tf1.getText().trim());
      double d2 = Double.parseDouble(tf2.getText().trim());
     
      if(ae.getSource()==pl)
      {
        lb4.setText(" ");  
        lb4.setText(Double.toString(d1+d2));    
      }
     
      if(ae.getSource()==mi)
      {
        lb4.setText(" ");  
        lb4.setText(Double.toString(d1-d2));
      }
     
      if (ae.getSource()==di)
      {
        lb4.setText(" ");  
        if (d2 == 0) {lb4.setText ("Division by zero NOT allowed!");}
        else
        {
          lb4.setText(Double.toString(d1/d2));
        }
      }
      if(ae.getSource()==mu)
      {
        lb4.setText(" ");  
       
        lb4.setText(Double.toString(d1*d2));
      }
    }
    catch(NumberFormatException nfe)
    {
      JOptionPane.showMessageDialog(this,"You must enter number in both

fields","Error",JOptionPane.ERROR_MESSAGE);
    }  
  }
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month19 days, 15 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question