0

I am trying to code a simple calculator like the one you would see in windows (non-scientific). I can not for the life of me figure out how to properly change the text after pressing an operator but still see the original entry that wont change until the next digit is pressed, have the equals key do the same operation if used multiple times (ie: 5+5 = 10 +5 = 15), and when I input a digit that is the same (5+5) it won't accept the second digit. I know I am very close and am probably missing a certain boolean that could allow my code to work properly, but Im not sure where to look. Thanks for any help.

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

public class JCalculator extends JFrame implements ActionListener {

/** intialize the jlabel, jbutton, string that makes the buttons and jpanel that will hold the buttons
 *
 */
private JTextField display = new JTextField("0", SwingConstants.RIGHT);
private JPanel buttonPanel = new JPanel();
private JPanel displayPanel = new JPanel();
private JButton newButton, divButton, multiButton, equalsButton, clearButton, plusButton, minusButton;
private String[] arrayButtons = {"7","8", "9", "/", "4", "5", "6", "x", "1", "2", "3", "-", "0","C", "=", "+"};
private int operand = 0;
private int firstInput = 0, secondInput = 0, answer = 0;




    JCalculator() {

        /** creates the jframe */
        JFrame jfrm = new JFrame("Calculator");

        /** sets the size of the jfrm and then positions it in the center of screen */
        jfrm.setSize(480, 300);
        jfrm.setLocationRelativeTo(null);

        /** sets the program to close on exit */
        jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
        /** ImageIcon img = new ImageIcon(JCalculator.png);
         *
         */

        /**sets initial layout to border */

        jfrm.setLayout(new BorderLayout());

        /** makes a panel named display that holds the Jtext display
         * enables it and justifies it right
         */
        displayPanel.setLayout(new BorderLayout());
        displayPanel.add(display, BorderLayout.CENTER);
        display.setHorizontalAlignment(JTextField.RIGHT);
        display.setEnabled(false);

        /** makes a panel for buttons that is a grid layout
         *
         */
        buttonPanel.setLayout(new GridLayout(4,4));

        /** makes a loop to make all of the 16 buttons for the calculator
         * the operands all have their own specific buttons
         */

        for (int i = 0; i < arrayButtons.length; i++) {

            if (arrayButtons[i].equals("/")) {

                divButton = new JButton(arrayButtons[i]);
                divButton.addActionListener(this);
                buttonPanel.add(divButton);

            } else if (arrayButtons[i].equals("x")) {

                multiButton = new JButton(arrayButtons[i]);
                multiButton.addActionListener(this);
                buttonPanel.add(multiButton);

            } else if (arrayButtons[i].equals("=")) {

                equalsButton = new JButton(arrayButtons[i]);
                equalsButton.addActionListener(this);
                buttonPanel.add(equalsButton);

            } else if (arrayButtons[i].equals("C")) {

                clearButton = new JButton(arrayButtons[i]);
                clearButton.addActionListener(this);
                buttonPanel.add(clearButton);

            } else if (arrayButtons[i].equals("+")) {

                plusButton = new JButton(arrayButtons[i]);
                plusButton.addActionListener(this);
                buttonPanel.add(plusButton);

            } else if (arrayButtons[i].equals("-")) {

                minusButton = new JButton(arrayButtons[i]);
                minusButton.addActionListener(this);
                buttonPanel.add(minusButton);

            } else {

                newButton = new JButton(arrayButtons[i]);
                newButton.addActionListener(this);
                buttonPanel.add(newButton);

            }
        }

        /** adds the two panels to the jfrm
         * sets jfrm visibility to true
         * sets equalsButton to the default button
         */
        jfrm.add(displayPanel, BorderLayout.NORTH);
        jfrm.add(buttonPanel, BorderLayout.CENTER);
        jfrm.getRootPane().setDefaultButton(equalsButton);
        jfrm.setVisible(true);
    }

public void actionPerformed(ActionEvent ae) {

    String s = ae.getActionCommand();
    char stringCheck = s.charAt(0);

    if (answer == Integer.parseInt(display.getText())) {

        display.setText("0");

    }

    if (Character.isDigit(stringCheck) && display.getText().length() < 8) {

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

            display.setText(s);

        } else {

        display.setText(display.getText().concat(s));

    }

    } if (s.equals("+")){

        answer = Integer.parseInt(display.getText());
        operand = 1;

    } if (s.equals( "-")){

        answer = Integer.parseInt(display.getText());
        operand = 2;

    } if (s.equals("x")){

        answer = Integer.parseInt(display.getText());
        operand = 3;

    } if (s.equals("/")){

        answer = Integer.parseInt(display.getText());
        operand = 4;

    } if (s.equals("C")){

        firstInput = 0;
        secondInput = 0;
        answer = 0;
        operand = 0;
        display.setText("0");

    } if (s.equals("=")){


        switch(operand){

            case 1:

            answer += Integer.parseInt(display.getText());
                display.setText(Integer.toString(answer));
            break;

            case 2:

            answer -= Integer.parseInt(display.getText());
                display.setText(Integer.toString(answer));
            break;

            case 3:

            answer *= Integer.parseInt(display.getText());
                display.setText(Integer.toString(answer));
            break;

            case 4:

                if(Integer.parseInt(display.getText()) > 0 || Integer.parseInt(display.getText()) < 0) {

                    answer /= Integer.parseInt(display.getText());
                    display.setText(Integer.toString(answer));
                    break;

                } else {

                    display.setText("Div by 0");

                }


        }

        if(answer > 100000000 || answer < -100000000){

            display.setText("Overlow");
        }

    }


}

public static void main (String [] args){

    /**
     * run program
     */
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new JCalculator();

        }
    });

 }
}
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
  • See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. – Andrew Thompson Sep 30 '18 at 05:39
  • @GhostCat can you explain what exactly isn't working? Because when using this it definitely runs. Just not in those specific examples.| Would posting the entire code help? Because Im having no issues with the string comparisons. – Graduation Sep 30 '18 at 05:41
  • @GhostCat I guess I'm confused as to why it's wrong if its comparing and its working. Sorry, I guess I don't fully understand what the issue is. I've read it though, and will try and make changes. – Graduation Sep 30 '18 at 05:51
  • @GhostCat its been fixed. If I messed up anything else please let me know. – Graduation Sep 30 '18 at 06:01
  • Looks better now. – GhostCat Sep 30 '18 at 06:34
  • "know I am very close and am probably missing a certain boolean", I do not think that, you did a good job, but still need to do some changes on actionPerformed method, you have to keep the value of the display.gettext(); before proceeding on updating it and doing the calculations , then concatenate the value to it and reset the display field after that – Ahmad Al-Kurdi Sep 30 '18 at 08:20

0 Answers0