Calculator without a decimal point

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TexasNewbie
    New Member
    • Dec 2006
    • 23

    Calculator without a decimal point

    This was originally just a calculator without a decimal point. After I added the decimal, it now tells me invalid second number.


    Code:
    //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[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;                                   //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': case '.':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();
        }
    }



    Please Help
    Last edited by r035198x; Jan 23 '07, 05:56 AM. Reason: OP forgot to put code tags
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Sorry Texas for the late reply. You were previously dealing with integers(withou t the decimal point).
    To capture integers Integer.parseIn t was used which was adequate. When you added the decimal point, Integer.parseIn t was no longer sufficient. You now need Double.parseDou ble and change your variables from int type to double type. I have made these changes below.


    Code:
    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;                                   //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': case '.':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
            {
                double num1 = Double.parseDouble(numStr1);// Changed here
                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;
                }
    
                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();
        }
    }

    Comment

    • TexasNewbie
      New Member
      • Dec 2006
      • 23

      #3
      I cant believe that it was something that I overlooked. A special thanks to r035198x, for not only looking over the code, but for helping me out.

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Originally posted by TexasNewbie
        I cant believe that it was something that I overlooked. A special thanks to r035198x, for not only looking over the code, but for helping me out.
        Just post any Java problems you get anytime. The guys here are always willing to help.

        Comment

        • TexasNewbie
          New Member
          • Dec 2006
          • 23

          #5
          further problem now I am getting infinity if I divide by zero. The exception should have caught it and given it an error : / by zero. Now, what have I forgotten?

          Comment

          • DeMan
            Top Contributor
            • Nov 2006
            • 1799

            #6
            In your evaluate() method, if the op is division, you should check that num2 != 0.0 (the program does not do this check for you because it is not an invalid number on parsing). you can do something like:

            Code:
            if(num2 == 0.0)
            {
              throw new ArithmeticException("Can't Divide by 0");
            }

            Comment

            • r035198x
              MVP
              • Sep 2006
              • 13225

              #7
              Originally posted by TexasNewbie
              further problem now I am getting infinity if I divide by zero. The exception should have caught it and given it an error : / by zero. Now, what have I forgotten?
              Tricky one for you this.

              Now dividing by (double) 0.0 does not cause an exception. The result is simply Infinity. This is because double are approximations and not exact values so 0.0 is a number as close to zero as possible....

              Dividing by (int) 0 is the one that throws the / by zero exception.

              Comment

              • TexasNewbie
                New Member
                • Dec 2006
                • 23

                #8
                Originally posted by r035198x
                Tricky one for you this.

                Now dividing by (double) 0.0 does not cause an exception. The result is simply Infinity. This is because double are approximations and not exact values so 0.0 is a number as close to zero as possible....

                Dividing by (int) 0 is the one that throws the / by zero exception.
                Now I'm really confused as to were I would insert the Dividing by (int) 0 or were I would put the throw exception to make this happen? I have tried install it in several places in the code and all I get is error after error. I'm really lost here!

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #9
                  Originally posted by TexasNewbie
                  Now I'm really confused as to were I would insert the Dividing by (int) 0 or were I would put the throw exception to make this happen? I have tried install it in several places in the code and all I get is error after error. I'm really lost here!
                  Code:
                  double num1 = Double.parseDouble(numStr1);// Changed here
                  double num2 = Double.parseDouble(numStr2);//
                  double result = 0;
                  These lines of code guarantee that you are never going to get a / by zero exception because you are now operating on doubles which give Infinity on / by zero rather than on ints which give that exception.

                  If you want to stop the program from getting infinity as a result then test the result with

                  Code:
                  if((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY)) {
                          System.out.println("error");
                  e.t.c
                  }

                  Comment

                  • TexasNewbie
                    New Member
                    • Dec 2006
                    • 23

                    #10
                    Okay, I put the statement were thought it should go but it still comes up infinity, any other hints clues suggestions? Or am I just an idiot? See below


                    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.set Size(200, 30);
                    displayText.set Location(10, 10);
                    pane.add(displa yText);
                    int x, y;
                    x = 10;
                    y = 40;
                    for (int ind = 0; ind < 20; ind++) {
                    button[ind] = new JButton(keys[ind]);
                    button[ind].addActionListe ner(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.addWindowL istener(new WindowAdapter() {
                    public void windowClosing(W indowEvent e) {
                    System.exit(0);
                    }
                    });

                    setVisible(true );
                    setDefaultClose Operation(EXIT_ ON_CLOSE);
                    }

                    public void actionPerformed (ActionEvent e) {
                    String resultStr; //Step 1
                    String str = String.valueOf( e.getActionComm and()); //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': case '.':if (firstInput)
                    {
                    numStr1 = numStr1 + ch;
                    displayText.set Text(numStr1);
                    }
                    else
                    {
                    numStr2 = numStr2 + ch;
                    displayText.set Text(numStr2);
                    }
                    break;
                    case '+': case '-': case '*': //Step 4b
                    case '/': op = ch;
                    firstInput = false;
                    break;
                    case '=': resultStr = evaluate(); //Step 4c
                    displayText.set Text(resultStr) ;
                    numStr1 = resultStr;
                    numStr2 = "";
                    firstInput = false;
                    break;
                    case 'C': displayText.set Text(""); //Step 4c
                    numStr1 = "";
                    numStr2 = "";
                    firstInput = true;
                    }
                    }

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

                    try
                    {
                    double num1 = Double.parseDou ble(numStr1);
                    double num2 = Double.parseDou ble(numStr2);
                    double result = 0;
                    if((result == Double.POSITIVE _INFINITY) || (result == Double.NEGATIVE _INFINITY))
                    {
                    System.out.prin tln("error");

                    }
                    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(Arithmeti cException e)
                    {
                    System.out.prin t(beep);
                    return "E R R O R:" + e.getMessage();
                    }
                    catch(NumberFor matException e)
                    {
                    System.out.prin t(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.prin t(beep);
                    return "E R R O R";
                    }
                    }

                    public static void main(String[] args)
                    {
                    Calculator C = new Calculator();
                    }
                    }
                    Last edited by TexasNewbie; Jan 25 '07, 06:11 PM. Reason: forgot some info

                    Comment

                    • r035198x
                      MVP
                      • Sep 2006
                      • 13225

                      #11
                      Makes sense to put it after the result is calculated
                      Code:
                      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.println("error");
                      return "E R R O R:" 
                      }
                      else {
                             return String.valueOf(result);
                      }
                              }
                              catch(ArithmeticException e)
                              {
                                  System.out.print(beep);	
                                  + e.getMessage();
                      	}
                      P.S Use code tags for posting code

                      Comment

                      • TexasNewbie
                        New Member
                        • Dec 2006
                        • 23

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

                        try
                        {
                        double num1 = Double.parseDou ble(numStr1);
                        double num2 = Double.parseDou ble(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.prin t(beep);
                        return "E R R O R:";
                        }
                        else
                        return String.valueOf( result);
                        }
                        catch(Arithmeti cException e)
                        {
                        System.out.prin t(beep);
                        }
                        catch(NumberFor matException e)
                        {
                        System.out.prin t(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.prin t(beep);
                        return "E R R O R";
                        }
                        finally
                        {
                        Calculator C = new Calculator();
                        }
                        } //line 153 this is the close for try
                        //line 154
                        } //line 155 this is te close for privat string

                        Okay, I am about as frustrated with this thing as I can be. I went back to the book thinking that there had to be a finally statement, but that didn't work I keep getting a missing return statement on line 153

                        Comment

                        • DeMan
                          Top Contributor
                          • Nov 2006
                          • 1799

                          #13
                          I Don't remember exactly how exceptions work, but I think your "finally" block is incorrect - can the code ever get here? (I think the compiler expects you to return a value here, which would be a fix, but I think the code will never reach this point so you should delete it).

                          Basically the "finally" is executed irrespective of which exception is thrown, but all of your exceptions have a return line which will stop execution of that method before it gets to finally.....

                          Comment

                          • Ganon11
                            Recognized Expert Specialist
                            • Oct 2006
                            • 3651

                            #14
                            Originally posted by TexasNewbie
                            Code:
                                    catch(ArithmeticException e)
                                      {
                                      System.out.print(beep);	
                                      }
                            This catch() block has no return statement, so it is possible that there will not be a return - this is why you get an error. Perhaps you should add the line

                            Code:
                            return "E R R O R";
                            as you have in other blocks.

                            Comment

                            • TexasNewbie
                              New Member
                              • Dec 2006
                              • 23

                              #15
                              I would like to thank everyone for thier input and let you know that I have resolved all issues with this project. New one to come soon. Expect to hear more from me. Thanks again.

                              Comment

                              Working...