Results 1 to 6 of 6
  1. #1
    klarnetbass22 is offline Member
    Join Date
    Feb 2014
    Posts
    3
    Rep Power
    0

    Default Extending my calculator

    Hello

    I am new to java and during my classes we built a basic calculator. I want to extend my calculator and added function to square numbers.

    Here is my program:
    Java Code:
    package calculator02;
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Calculator02 extends JFrame{
          private Container guiContainer;
          private String title = "Calculator Version 2";
          // window components
          private JLabel inputLabel = new JLabel("Calculation");
          private JTextField inputTextField = new JTextField(15);
          private JPanel inputPanel = new JPanel();
          private JPanel operationButtonPanel = new JPanel();
          private JPanel selectionButtonPanel = new JPanel();
          private JButton plus = new JButton("+");
          private JButton minus = new JButton("-");
          private JButton multiply = new JButton("*");
          private JButton divide = new JButton("/");
          private JButton equals = new JButton("=");
          private JButton cancel = new JButton("C");
          private JButton square = new JButton("^2");
          
          private JButton one = new JButton("1");
          private JButton two = new JButton("2");
          private JButton three = new JButton("3");
          private JButton four = new JButton("4");
          private JButton five = new JButton("5");
          private JButton six = new JButton("6");
          private JButton seven = new JButton("7");
          private JButton eight = new JButton("8");
          private JButton nine = new JButton("9");
          private JButton zero = new JButton("0");
          private JButton blank = new JButton(" ");
          private JButton dot = new JButton(".");
          
          private String currentData = "";
    
          // window properties
          private static final int FRAMEWIDTH = 400;
          private static final int FRAMEHEIGHT = 330;
          private static final int FRAMEX = 200; // screen co-ordinates
          private static final int FRAMEY = 150;
          
          private static final double MAX_VALUE = 1000000000;
          
          // class attributes
          String operator = "";
          String initialOperator = "";
          String storedOperator = "";
          double preOperand = MAX_VALUE;
          double postOperand = MAX_VALUE;
          double total = 0;
          boolean boxAvailable = true;
          
      
        /** Creates a new instance of Calculator02 */
        public Calculator02() {
            guiContainer = getContentPane();
            setTitle(title);
            // add panels to frame using BorderLayout
            guiContainer.add(inputPanel, BorderLayout.NORTH);
            guiContainer.add(selectionButtonPanel, BorderLayout.CENTER);
            guiContainer.add(operationButtonPanel, BorderLayout.SOUTH);
            // add components to panels
            inputPanel.add(inputLabel);
            inputPanel.add(inputTextField);
            // no need for user to input text directly
            inputTextField.setEditable(false);
            operationButtonPanel.add(plus);
            operationButtonPanel.add(minus);
            operationButtonPanel.add(multiply);
            operationButtonPanel.add(divide);
            operationButtonPanel.add(equals);
            operationButtonPanel.add(cancel);
            operationButtonPanel.add(square);
            
            selectionButtonPanel.setLayout(new GridLayout(4, 3));
            selectionButtonPanel.add(seven);
            selectionButtonPanel.add(eight);
            selectionButtonPanel.add(nine);
            selectionButtonPanel.add(four);
            selectionButtonPanel.add(five);
            selectionButtonPanel.add(six);
            selectionButtonPanel.add(one);
            selectionButtonPanel.add(two);
            selectionButtonPanel.add(three);
            selectionButtonPanel.add(zero);
            selectionButtonPanel.add(blank);
            blank.setVisible(false);
            selectionButtonPanel.add(dot);
            
            // create a listener
            OperationButtonListener oBListener = new OperationButtonListener();
            SelectionButtonListener sBListener = new SelectionButtonListener();
            // assign listener to buttons
            plus.addActionListener(oBListener);
            minus.addActionListener(oBListener);
            multiply.addActionListener(oBListener);
            divide.addActionListener(oBListener);
            equals.addActionListener(oBListener);
            cancel.addActionListener(oBListener);
            square.addActionListener(oBListener);
            
            zero.addActionListener(sBListener);
            one.addActionListener(sBListener);
            two.addActionListener(sBListener);
            three.addActionListener(sBListener);
            four.addActionListener(sBListener);
            five.addActionListener(sBListener);
            six.addActionListener(sBListener);
            seven.addActionListener(sBListener);
            eight.addActionListener(sBListener);
            nine.addActionListener(sBListener);
            dot.addActionListener(sBListener);
        }
         
         private class SelectionButtonListener implements ActionListener  {
          public void actionPerformed(ActionEvent event) {
           String choice = event.getActionCommand();
           if(boxAvailable)
               inputTextField.setText(inputTextField.getText().concat(choice));
           else {
               boxAvailable = true;
               inputTextField.setText(""); 
               inputTextField.setText(inputTextField.getText().concat(choice));
           }
          }
         }
    
        private class OperationButtonListener implements ActionListener  {
          public void actionPerformed(ActionEvent event) {
           String choice = event.getActionCommand();
           if(choice.equals("+")) {
               operator = "+";
               if(preOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPreOperand(currentData))
                    initialOperator = operator;
               }
                else if(postOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    storedOperator = operator; 
                    processOperator(initialOperator);
                }
            } 
            else { 
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    processOperator(storedOperator);
                    storedOperator = operator;
                }
            }
           }
           else if(choice.equals("-")) {
               operator = "-";
               if(preOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPreOperand(currentData))
                    initialOperator = operator;
               }
                else if(postOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    storedOperator = operator; 
                    processOperator(initialOperator);
                }
            } 
            else { 
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    processOperator(storedOperator);
                    storedOperator = operator;
                }
            }
           }
           else if(choice.equals("*")) {
               operator = "*";
               if(preOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPreOperand(currentData))
                    initialOperator = operator;
               }
                else if(postOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    storedOperator = operator; 
                    processOperator(initialOperator);
                }
            } 
            else { 
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    processOperator(storedOperator);
                    storedOperator = operator;
                }
            }
          }
           else if(choice.equals("/")) {
              operator = "/";
               if(preOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPreOperand(currentData))
                    initialOperator = operator;
               }
                else if(postOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    storedOperator = operator; 
                    processOperator(initialOperator);
                }
            } 
            else { 
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    processOperator(storedOperator);
                    storedOperator = operator;
                }
            } 
          }
           else if(choice.equals("^2")) {
              operator = "^2";
               if(preOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPreOperand(currentData))
                    initialOperator = operator;
               }
                else if(postOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    storedOperator = operator; 
                    processOperator(initialOperator);
                }
            } 
            else { 
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    processOperator(storedOperator);
                    storedOperator = operator;
                }
            } 
          }
           
          
           else if(choice.equals("=")) {
               operator = "=";
               // handled slightly differently to others
               if(preOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPreOperand(currentData)) {
                    initialOperator = operator;
                    total = preOperand; // assign total immediately
                    checkwhole();
                }
               }
                else if(postOperand == MAX_VALUE){
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    storedOperator = operator; 
                    processOperator(initialOperator);
                }
            } 
            else {
                currentData = inputTextField.getText();
                if(convertPostOperand(currentData)) {
                    processOperator(storedOperator);
                    storedOperator = operator;
                 }
            }
          }
           else if(choice.equals("C")) {
               preOperand = MAX_VALUE;
               postOperand = MAX_VALUE; 
               total = 0;
               operator = "";
               initialOperator = "";
               storedOperator = "";
               inputTextField.setText("");
          }
           boxAvailable = false; //to force clear text field for next user input
        }
      }
        
        
        // following class methods provide processing utilities to handle
        // user input
        
        // string extracted from text field passed as argument which
        // is converted to a double and stored in class attribute preOperand
        // try .. catch block traps number format errors
        private boolean convertPreOperand(String value){    
            try{
                preOperand = Double.parseDouble(value);
            } catch(NumberFormatException e1) {
            JOptionPane.showMessageDialog(null, "Wrong Number Format\n " + e1,
                                          "Input Error", JOptionPane.ERROR_MESSAGE);
            return false;
            }
            return true;
        }
            
        // string extracted from text field passed as argument which
        // is converted to a double and stored in class attribute postOperand
        // try .. catch block traps number format errors
        private boolean convertPostOperand(String value){      
            try{
                postOperand = Double.parseDouble(value);
            } catch(NumberFormatException e1) {
            JOptionPane.showMessageDialog(null, "Wrong Number Format\n " + e1,
                                          "Input Error", JOptionPane.ERROR_MESSAGE);
            return false;
            }
            return true;
         }
        
    
         private void checkwhole() {
        if( total - (int)total != 0)
          inputTextField.setText(Double.toString(total)); 
        else
          inputTextField.setText(Integer.toString((int)total));       
     }  
        // updates class attribute total in accordance with operator
        // passed as an argument; preOperand and text field also updated
        private void processOperator(String operator) {
            if(operator.equals("+")){
                total = preOperand + postOperand;
            }
            else if(operator.equals("-")){
                total = preOperand - postOperand;
            }
            else if(operator.equals("*")){
                total = preOperand * postOperand;
            }
            else if(operator.equals("/")){
                if(postOperand != 0)
                    total = preOperand / postOperand;
            else if(operator.equals("^2")){
                if(postOperand != 0)
                    total = Math.pow(preOperand, 2);
            }
                else
                    JOptionPane.showMessageDialog(null, "Error. Cannot divide by 0\n " +
                                                  "Operation ignored");
            }
            preOperand = total;
           checkwhole(); 
        }
            
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // create, size, and position window
            Calculator02 calculator02 =
                     new Calculator02();
            calculator02.pack();
            calculator02.setVisible(true);
            calculator02.setSize(FRAMEWIDTH, FRAMEHEIGHT);
            calculator02.setLocation(FRAMEX, FRAMEY);
            calculator02.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        
    }
    The problem I want to solve is that every time I hit square button i also have to hit equal button to answer to be shown. I can't think of a way to make the result appear instantly after pressing ^2 button.
    For adding, substracting, multiplicating and dividing you need 2 numbers but for squaring you only need 1 number and that why i don't want to be forced to hit equal every time I want my answer.

    Any suggestions on how might I do this ? I personally have no idea.

    PS I hope my english is understandable
    PPS I tried to search forum for any existing problem but gave up after 200th result.
    PPPS My first thread, if there is anything wrong with it, please tell me

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    947
    Rep Power
    2

    Default Re: Extending my calculator

    What about equals.doClick()?
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2™ © 2013

  3. #3
    klarnetbass22 is offline Member
    Join Date
    Feb 2014
    Posts
    3
    Rep Power
    0

    Default Re: Extending my calculator

    Quote Originally Posted by SurfMan View Post
    What about equals.doClick()?
    Could you please expand this and try to explain this to me ? As I said I am still confused about many things because I am fairly new to Java.

  4. #4
    AlexGraal is offline Señor Member
    Join Date
    Jan 2014
    Posts
    184
    Rep Power
    0

    Default Re: Extending my calculator

    Ok, I don't have any experience with this, so I may be wrong, but I'm assuming he means this:

    Artificially "click" the = buttons after a person clicks the ^2 button.

    Maybe that is what equals.doClick() does?

    My approach would be to just trigger the "=" button after the "^2" button is pressed.

  5. #5
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    947
    Rep Power
    2

    Default Re: Extending my calculator

    Quote Originally Posted by AlexGraal View Post
    My approach would be to just trigger the "=" button after the "^2" button is pressed.
    And that is exactly what equals.doClick() does. It simulates the click on the equals button. You should put this in with your ^2 code. While we're at it, I know it's a personal choice of how curly braces are placed. (For every 1000 programmers there's 1000 prefrences). But one thing I would recommend with a passion is to always put curly braces around if-blocks.

    This is your pow code:
    Java Code:
    if(postOperand != 0)
             total = Math.pow(preOperand, 2);
    If you add equals().doClick() after it, you might be in for some surprises:
    Java Code:
    if(postOperand != 0)
             total = Math.pow(preOperand, 2);
             equals.doClick();
    Since the curly braces are missing, only the total = Math... will be executed. You have to remember to add the curly braces every time you have more than one statement for the if-block. This will lead to bugs very quickly.

    Java Code:
    if(postOperand != 0) {
             total = Math.pow(preOperand, 2);
             equals.doClick();
    }
    PS: Since the pow code is executed via an inner class, your editor will probably nag that the equals JButton must be made final. This is ok, and a side effect of using inner classes.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2™ © 2013

  6. #6
    klarnetbass22 is offline Member
    Join Date
    Feb 2014
    Posts
    3
    Rep Power
    0

    Default Re: Extending my calculator

    Thank you very much, I understand this and seems so simple.

    It works perfectly for me.

Similar Threads

  1. Extending problems...
    By Alkor in forum New To Java
    Replies: 5
    Last Post: 02-26-2012, 01:18 AM
  2. Using JTable without extending or overriding
    By adra in forum New To Java
    Replies: 7
    Last Post: 08-29-2011, 04:22 AM
  3. Extending Classes and What is Necessary
    By GavinCash in forum New To Java
    Replies: 10
    Last Post: 10-11-2010, 07:07 AM
  4. Extending or changing DTD for validator
    By dbil in forum Web Frameworks
    Replies: 0
    Last Post: 10-09-2009, 10:54 AM
  5. Implementing and Extending together
    By eva in forum New To Java
    Replies: 2
    Last Post: 12-24-2007, 09:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •