0

So after clicking a function button my programs stores the current number(num1) on the calculator and then stores what function was selected. When the equals button is pressed it should determine what the last function selected was and apply it to the previous number and the current number(num2) and display the solution please help.

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

public class Calculator extends JFrame implements ActionListener{
    JTextField input;
    JMenuBar menubar;
    JMenu file,help;
    JMenuItem exit;
    JButton clear,backspace,bDecimal,bDivide,bMult,bMinus,bPlus,bEquals,bNegative,bSqrt,bInverse;
    JButton b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;
    Double num1,num2 = null;
    JPanel numPanel,fcnPanel,outPanel;

    public Calculator(){
        //Make the frame
        this.setPreferredSize(new Dimension(909,909));
        this.setTitle("Vlad's Swing Calculator");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setLayout(new GridBagLayout());
        this.getContentPane().setBackground(Color.GREEN);

        //Create the menubar
        menubar = new JMenuBar();
        this.setJMenuBar(menubar);
        //menus
        file = new JMenu("File");
        menubar.add(file);
        help = new JMenu("Help");
        menubar.add(help);
        //menuItem
        exit = new JMenuItem("Exit");
        exit.addActionListener(this);
        file.add(exit);

        //Create text field
        input = new JTextField("",10);
        input.setBackground(Color.WHITE);
        input.setEditable(false);

        //create buttons
        clear = new JButton("Clear");
        backspace = new JButton("Backspace");
        b0 = new JButton(" 0 ");
        b1 = new JButton(" 1 ");
        b2 = new JButton(" 2 ");
        b3 = new JButton(" 3 ");
        b4 = new JButton(" 4 ");
        b5 = new JButton(" 5 ");
        b6 = new JButton(" 6 ");
        b7 = new JButton(" 7 ");
        b8 = new JButton(" 8 ");
        b9 = new JButton(" 9 ");
        bDecimal = new JButton(" .  ");
        bDivide = new JButton("/");
        bMult = new JButton("*");
        bMinus = new JButton("-");
        bPlus = new JButton("+");
        bEquals = new JButton("=");
        bNegative = new JButton("+/-");
        bSqrt = new JButton("sqrt");
        bInverse = new JButton("1/x");

        //add action listeners
        clear.addActionListener(this);
        backspace.addActionListener(this);
        b0.addActionListener(this);
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        b5.addActionListener(this);
        b6.addActionListener(this);
        b7.addActionListener(this);
        b8.addActionListener(this);
        b9.addActionListener(this);
        bDecimal.addActionListener(this);
        bDivide.addActionListener(this);
        bMult.addActionListener(this);
        bMinus.addActionListener(this);
        bPlus.addActionListener(this);
        bEquals.addActionListener(this);
        bNegative.addActionListener(this);
        bSqrt.addActionListener(this);
        bInverse.addActionListener(this);


        //Add buttons to panel
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(2,2,2,2);
        //add text field
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        this.add(input,gbc);

        //add numbers 0-9
        numPanel = new JPanel();
        numPanel.setLayout(new GridLayout(4,3));
        numPanel.add(b7);
        numPanel.add(b8);
        numPanel.add(b9);
        numPanel.add(b4);
        numPanel.add(b5);
        numPanel.add(b6);
        numPanel.add(b1);
        numPanel.add(b2);
        numPanel.add(b3);
        numPanel.add(b0);
        numPanel.add(bNegative);
        numPanel.add(bDecimal);


        // //Add function buttons
        fcnPanel = new JPanel();

        fcnPanel.setLayout(new GridLayout(4,2));
        fcnPanel.add(bSqrt);
        fcnPanel.add(bInverse);
        fcnPanel.add(bNegative);
        fcnPanel.add(bMinus);
        fcnPanel.add(bPlus);
        fcnPanel.add(bDivide);
        fcnPanel.add(bMult);
        fcnPanel.add(bEquals);

        //Add backspace and clear
        outPanel = new JPanel();
        outPanel.setLayout(new GridLayout(2,1));
        outPanel.add(clear);
        outPanel.add(backspace);

        this.add(outPanel);
        this.add(numPanel);
        this.add(fcnPanel);
        this.pack();

    }

    @Override
    public void actionPerformed(ActionEvent e){
        Object buttonPressed = e.getSource();
        Object lastButtonPressed = null;
        if(buttonPressed == exit){
            System.exit(0);
        }
        //Add action for clear
        if(buttonPressed == clear){
            input.setText("");
            num1 = num2 = null;
        }
        //Add action for backspace
        if(buttonPressed == backspace){
            String lastElementRemoved = input.getText();
            lastElementRemoved = lastElementRemoved.substring(0,lastElementRemoved.length()-1);
            input.setText(lastElementRemoved);
        }

        //Add event for each integer button
        if(buttonPressed == b0){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "0")
            {
                input.setText("0");
            }
            else
                input.setText(input.getText() + "0");
        }
        if(buttonPressed == b1){
            if(input.getText() == "0"){
                input.setText("1");
            }
            else
                input.setText(input.getText() + "1");
        }
        if(buttonPressed == b2){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "2")
            {
                input.setText("2");
            }
            else
                input.setText(input.getText() + "2");
        }
        if(buttonPressed == b3){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "3")
            {
                input.setText("3");
            }
            else
                input.setText(input.getText() + "3");
        }
        if(buttonPressed == b4){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "4")
            {
                input.setText("4");
            }
            else
                input.setText(input.getText() + "4");
        }
        if(buttonPressed == b5){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "5")
            {
                input.setText("5");
            }
            else
                input.setText(input.getText() + "5");
        }
        if(buttonPressed == b6){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "6")
            {
                input.setText("6");
            }
            else
                input.setText(input.getText() + "6");
        }
        if(buttonPressed == b7){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "7")
            {
                input.setText("7");
            }
            else
                input.setText(input.getText() + "7");
        }
        if(buttonPressed == b8){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "8")
            {
                input.setText("8");
            }
            else
                input.setText(input.getText() + "8");
        }
        if(buttonPressed == b9){
            //Make sure the starting zero will not be prepended
            if(input.getText() == "9")
            {
                input.setText("9");
            }
            else
                input.setText(input.getText() + "9");
        }

        //Add function for decimanl button
        if(buttonPressed == bDecimal){
            input.setText(input.getText() + ".");
        }
        //Add function for divide button
        if(buttonPressed == bDivide){
            lastButtonPressed = bDivide;
            num1 = Double.parseDouble(input.getText());
            input.setText("");
        }
        //Add Function for multiply button
        if(buttonPressed == bMult){
            lastButtonPressed = bMult;
            num1 = Double.parseDouble(input.getText());
            input.setText("");
        }
        //Add function to minus button
        if(buttonPressed == bMinus){
            lastButtonPressed = bMinus;
            num1 = Double.parseDouble(input.getText());
            input.setText("");
        }

        //Add function to plus button
        if(buttonPressed == bPlus){
            lastButtonPressed = bPlus;
            num1 = Double.parseDouble(input.getText());
            input.setText("");
        }
        //Add function for equals button
        if(buttonPressed == bEquals){
            //retrieve num2
            num2 = Double.parseDouble(input.getText());

            if(lastButtonPressed == bDivide){
                num1 = num1/num2;
                input.setText(num1.toString());
            }
            if(lastButtonPressed == bMult){
                num1 = num1*num2;
                input.setText(num1.toString());
            }
            if(lastButtonPressed == bMinus){
                num1 = num1-num2;
                input.setText(num1.toString());
            }
            if(lastButtonPressed == bPlus){
                num1 = num1+num2;
                input.setText(num1.toString());
            }
            else
                return;
        }

    }

    public static void main(String[] args){
        Calculator calc = new Calculator();
        calc.setVisible(true);
    }
}

I don't think the code in the equals part is being executed because a println I put under if(lastButtonPressed == bDivide) did not print.

So it turns out that lastButtonPressed is not being updated. Not sure why.

  • So what is happening? Does the code get executed? Did you use a debugger to step through the code or add display statements in each if statement to see what is being executed? To you display the value that is being calculated? You need to tell us what is happening in addition to what should happen. – camickr Oct 30 '18 at 02:24
  • Also, don't use a single ActionListener for all the buttons. Buttons with similar functionality can share a generic listener. Buttons with unique functionality should have a separate listener. Check out: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732 for an example that shows how to share an Action for multiple buttons. – camickr Oct 30 '18 at 02:36
  • When I click equals the result is not output. When I put a println for num1 or num2 nothing shows up in console. Is that because I am compiling with javaw? – Vlad Shluharchuk Oct 30 '18 at 02:36
  • Don't add comments. The question should be improved by updating the question with relevant information so all the information is in one place. `When I click equals the result is not output` - you still didn't answer my question. Is the code executed? `Is that because I am compiling with javaw?` - you are not compiling with javaw, you are executing your class file with javaw and yes, when you use javaw the output is not displayed. Use "java". – camickr Oct 30 '18 at 02:42
  • Am I supposed to initialize Object lastButtonPressed to something other than null in order for it to update properly? – Vlad Shluharchuk Oct 30 '18 at 02:54
  • See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. – Andrew Thompson Oct 30 '18 at 06:43

1 Answers1

0

So it turns out that lastButtonPressed is not being updated

public void actionPerformed(ActionEvent e)
{
    Object buttonPressed = e.getSource();
    Object lastButtonPressed = null;

It is being updated but the problem is you update the value and then the next time the ActionListener is invoked you reset the value to null.

So every time the ActionListener is invoke you lose the information about the last button that was pressed.

Also, don't use "==" to compare strings.

if(input.getText() == "0"){

Instead use the equals(...) method.

if ("0".equals(input.getText()) {

Note I also reversed the order. This will prevent errors in case the input.getText() method ever return a null object.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • In addition to re-opening this question I feel that at least some mention of how the OP is comparing Strings is warranted – Scary Wombat Oct 30 '18 at 04:58