I was instructed in class to do the following....

The Programming Example: Calculator in Chapter 12 is designed to do operations on integers. Write a similar program that can be used to do operations on decimal numbers. (Note: If division by zero occurs with values of the int data type, the program throws a division by zero exception. However, if you divide a decimal number by zero, Java does not throw the division by zero exception; it returns the answer as infinity. However, if division by zero occurs, your calculator program must output the message ERROR: / by zero.)

I kept the same program as the example and changed the int to doubles. I put in statements to eliminate the infinity result for double by zero results. Where I'm confused is did I do this correct by every result resulting in ERROR: / by zero or is this asking me for 3 different types of error depending on division by 0, 0.0, and zero exception? If so I can't seem to make that work. I kind of see it as the program will result in infinity or ERROR: / by zero but not both options in the same program. I'm completely confused.

My code is as follows......

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
 
public class Calculator extends JFrame implements ActionListener
 {
    private JTextField displayText = new JTextField(30);
    private JButton[] button = new JButton[20];
	 
    private String[] keys ={"7", "8", "9", "/",
                            "4", "5", "6", "*",
                            "1", "2", "3", "-",
                            "0", "C", "=", "+",
                             ".", " ", " ", " "};
    private String numStr1 = "";
    private String numStr2 = "";
	 
    private char op;
    private boolean firstInput = true;
	 
    public Calculator()
     {
        setTitle("My Calculator");
        setSize(230, 250);
        Container pane = getContentPane();
		  
        pane.setLayout(null);
		  
        displayText.setSize(200, 30);
        displayText.setLocation(10, 10);
        pane.add(displayText);
		  
        int x, y;
		  
        x = 10;
        y = 40;
        for (int ind = 0; ind < 20; ind++)
       {
            button[ind] = new JButton(keys[ind]);
            button[ind].addActionListener(this);
            button[ind].setSize(50, 30);
            button[ind].setLocation(x, y);
            pane.add(button[ind]);
            x = x + 50;
            if((ind + 1) % 4 == 0) 
				{
                x = 10;
                y = y + 30;
            }
        }
 
        this.addWindowListener(new WindowAdapter() 
                      {
                           public void windowClosing(WindowEvent e)
                           {
                                System.exit(0);
                           }
                      }
		  );
 
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
 
   public void actionPerformed(ActionEvent e)
   {
        String resultStr;                                  
        String str = String.valueOf(e.getActionCommand()); 
		  
        char ch = str.charAt(0);   
		                          
        switch (ch)                                     
        {
        case '0': case '1': case '2':                 
        case '3': case '4': case '5':
        case '6': case '7': case '8':
        case '9': case '.':if (firstInput)
                  {
                      numStr1 = numStr1 + ch;
                      displayText.setText(numStr1);
                  }
                    else
                  {
                      numStr2 = numStr2 + ch;
                      displayText.setText(numStr2);
                  }
                  break;
        case '+': case '-': case '*':                    
        case '/': op = ch;
                  firstInput = false;
                  break;
        case '=': resultStr = evaluate();                
                  displayText.setText(resultStr);
                  numStr1 = resultStr;
                  numStr2 = "";
                  firstInput = false;
                  break;
        case 'C': displayText.setText("");                 
                  numStr1 = "";
                  numStr2 = "";
                  firstInput = true;
      }
    }
 
    private String evaluate()
    {
        final char beep = '\u0007';
 
        try
        {
            double num1 = Double.parseDouble(numStr1);
            double num2 = Double.parseDouble(numStr2);
            double result = 0;
 
            switch (op)
               {
               case '+': result = num1 + num2;
                      break;
               case '-': result = num1 - num2;
                      break;
               case '*': result = num1 * num2;
                      break;
               case '/': result = num1 / num2;
               }
        if ((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY))
        {
            System.out.print(beep);
            return "E R R O R: / by zero";
        }
          else
            return String.valueOf(result);
        }
        catch(ArithmeticException e)
        {
            System.out.print(beep);
            return "E R R O R:";    
        }
        catch(NumberFormatException e)
        {
            System.out.print(beep);
            if (numStr1.equals(""))
               return "E R R O R: Invalid First Number" ;
            else
               return "E R R O R: Invalid Second Number" ;
        }
        catch(Exception e)
        {
            System.out.print(beep);
            return "E R R O R"; 
        }
    }
	 
    public static void main(String[] args)
    {
        Calculator C = new Calculator();
    }
 
}

This is the original code if it helps.

//GUI Calculator Program

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

public class Calculator extends JFrame implements ActionListener
{
    private JTextField displayText = new JTextField(30);
    private JButton[] button = new JButton[16];

    private String[] keys = {"7", "8", "9", "/",
                            "4", "5", "6", "*",
                            "1", "2", "3", "-",
                            "0", "C", "=", "+"};

    private String numStr1 = "";
    private String numStr2 = "";

    private char op;
    private boolean firstInput = true;

    public Calculator()
    {
        setTitle("My Calculator");
        setSize(230, 200);
        Container pane = getContentPane();

        pane.setLayout(null);

        displayText.setSize(200, 30);
        displayText.setLocation(10, 10);
        pane.add(displayText);

        int x, y;

        x = 10;
        y = 40;
        for (int ind = 0; ind < 16; ind++)
        {
            button[ind] = new JButton(keys[ind]);
            button[ind].addActionListener(this);
            button[ind].setSize(50, 30);
            button[ind].setLocation(x, y);
            pane.add(button[ind]);
            x = x + 50;
            if((ind + 1) % 4 == 0)
            {
                x = 10;
                y = y + 30;
            }
        }

        this.addWindowListener(new WindowAdapter()
                      {
                           public void windowClosing(WindowEvent e)
                           {
                                System.exit(0);
                           }
                    }
        );

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e)
    {
        String resultStr;                                   //Step 1
        String str = String.valueOf(e.getActionCommand());  //Steps 1 and 2

        char ch = str.charAt(0);                            //Steps 1 and 3

        switch (ch)                                          //Step 4
        {
        case '0': case '1': case '2':                       //Step 4a
        case '3': case '4': case '5':
        case '6': case '7': case '8':
        case '9': if (firstInput)
                  {
                     numStr1 = numStr1 + ch;
                     displayText.setText(numStr1);
                  }
                  else
                  {
                      numStr2 = numStr2 + ch;
                      displayText.setText(numStr2);
                  }
                  break;
        case '+': case '-': case '*':                       //Step 4b
        case '/': op = ch;
                  firstInput = false;
                  break;
        case '=': resultStr = evaluate();                   //Step 4c
                  displayText.setText(resultStr);
                  numStr1 = resultStr;
                  numStr2 = "";
                  firstInput = false;
                  break;
        case 'C': displayText.setText("");                  //Step 4c
                  numStr1 = "";
                  numStr2 = "";
                  firstInput = true;
        }
    }

    private String evaluate()
    {
        final char beep = '\u0007';

        try
        {
            int num1 = Integer.parseInt(numStr1);
            int num2 = Integer.parseInt(numStr2);
            int result = 0;

            switch (op)
            {
            case '+': result = num1 + num2;
                      break;
            case '-': result = num1 - num2;
                      break;
            case '*': result = num1 * num2;
                      break;
            case '/': result = num1 / num2;
            }

            return String.valueOf(result);
        }
        catch(ArithmeticException e)
        {
            System.out.print(beep);
            return "E R R O R: " + e.getMessage();
        }
        catch(NumberFormatException e)
        {
            System.out.print(beep);
            if (numStr1.equals(""))
               return "E R R O R: Invalid First Number" ;
            else
               return "E R R O R: Invalid Second Number" ;
        }
        catch(Exception e)
        {
            System.out.print(beep);
            return "E R R O R";
        }
    }

    public static void main(String[] args)
    {
        Calculator C = new Calculator();
    }
}

BUMP....Anyone able to review my code and help?

I executed your code and it works.

What is your problem?

Thanks for the reply I'm just worried that I'm not understanding the problem maybe I'm over thinking it. Did I do this project correctly by eliminating the infinity, NaN answers for dividing an integer by zero? Thanks

Thanks for the reply I'm just worried that I'm not understanding the problem maybe I'm over thinking it. Did I do this project correctly by eliminating the infinity, NaN answers for dividing an integer by zero? Thanks

Well I didn't test it thoroughly, so when you get the errors, what input do you enter, does it display and what do you want it to display?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.