This is code for a simple calculator. Can someone review it, so I can know if there is something wrong? I also want to know if I can link a keybinding to a JButton so I don't have to write an actionlistner for a JButton enterBut. I already tested it several times and it works fine.Also, someone told me yesterday that I shouldn't use a foreach loop to assign a value to my null Button array, and instead I need to use a for loop. Can someone explain why? Also, if there is a way to get rid all of the if statements in the calculate method, please tell me.import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import javax.swing.AbstractAction;import javax.swing.ActionMap;import javax.swing.InputMap;import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.KeyStroke;class Window6 {    private JFrame frame = new JFrame();    private JTextField screen = new JTextField();    private final String[] numberText  = {7,8,9,4,5,6,1,2,3,0,.,c};    private final String[] functionText = {+, -, *, /};    private final JButton numberButton[] = new JButton[numberText.length];    private final JButton functionButton[] = new JButton[functionText.length];    private JButton equalBut = new JButton(=);    private JPanel numberPanel = new JPanel();    private JPanel functionPanel = new JPanel();    private JPanel panel = new JPanel();    public Window6() {        JPanel temp = new JPanel();        numberPanel.setLayout(new GridLayout(4,3));        functionPanel.setLayout(new GridLayout(2, 2));        int index = 0;        for(JButton x : functionButton) {            x = new JButton();            x.setText(functionText[index]);            x.addActionListener(new ActionListener() {                public void actionPerformed(ActionEvent e) {                    JButton temp = (JButton)e.getSource();                     screen.setText(screen.getText() + temp.getText());                }            });            functionPanel.add(x);            index++;        }        index =0;        InputMap im = equalBut.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), submit);        ActionMap ap = equalBut.getActionMap();        ap.put(submit, new AbstractAction() {            @Override            public void actionPerformed(ActionEvent e) {                calculate();            }        });        equalBut.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                calculate();            }        });        for(JButton x : numberButton) {            x = new JButton();            x.setText(numberText[index]);            x.addActionListener(new ActionListener() {                public void actionPerformed(ActionEvent e) {                    JButton temp = (JButton)e.getSource();                    if(!c.equals(temp.getText())) {                        screen.setText(screen.getText() + temp.getText());                    } else {                        screen.setText();                    }                }            });            numberPanel.add(x);                index++;        }           temp.setLayout(new GridLayout(2, 1));        temp.add(this.functionPanel);        temp.add(this.equalBut);        screen.setPreferredSize(new Dimension(200,100));        frame.add(screen, BorderLayout.NORTH);        panel.setLayout(new GridLayout(1,2));        panel.add(numberPanel);        panel.add(temp);        frame.add(panel, BorderLayout.CENTER);        frame.setSize(300, 400);        frame.setVisible(true);    }    private void calculate() {        String str = screen.getText();        String number[] = str.split([+||\\-||*||/]);        int index = number[0].length();        String sign = str.substring(index, index + 1);        System.out.println(sign);        if (-.equals(sign)) {        try {            float x = Float.parseFloat(number[0]);            float y = Float.parseFloat(number[1]);            screen.setText(String.valueOf(x - y));        } catch (Exception e){            screen.setText(Please enter numbers);        }        } else if (+.equals(sign)) {            try {                float x = Float.parseFloat(number[0]);                float y = Float.parseFloat(number[1]);                screen.setText(String.valueOf(x + y));            } catch (Exception e){                screen.setText(Please enter numbers);            }        } else if (*.equals(sign)) {            try {                float x = Float.parseFloat(number[0]);                float y = Float.parseFloat(number[1]);                screen.setText(String.valueOf(x * y));            } catch (Exception e){                screen.setText(Please enter numbers);            }        } else if (/.equals(sign)) {            try {                float x = Float.parseFloat(number[0]);                float y = Float.parseFloat(number[1]);                screen.setText(String.valueOf(x / y));            } catch (Exception e){                screen.setText(Please enter numbers);            }        }    }}public class hw6 {    public static void main(String args[]) {        new Window6();    }}
Simple calculator about keybinding
java;beginner
Thank you for sharing your code![Is] there is a way to get rid all of the if statements in the calculate method?This program lags a clear MVC hierarchy. This results in a somwhat procedural approach in the calculate() where you mix business behavior with access to View elements.A proper OO approach would start with the  function buttons. The actions they trigger have the same interface (2 numbers input, one number output). But each of them causes a different calculation aka different behavior. In OOP different behavior means different classes:interface CalculatorFunction{   float caculate(float a, float b);}class FunctionAdd implements CalculatorFunction{   float caculate(float summandA, float summandB){     return summandA + summandB;  }}class OperationFunction implements CalculatorFunction{   float caculate(float minuend, float subtrahend){     return minuend-subtrahend;  }}// same for other functionsIn your Model  layer you should create a variable holding an instance of this interface: privat static final CalculatorFunction NO_CALCULATION = (a,b)->throw new IlligelArgumentException(no operation selected); private CalculatorFunction function = NO_CALCULATION;Having This you need to assign each function button its action individually: JButton buttonAdd = new JButton(new AbstractAction(+){    public void actionPerformed(ActionEvent e) {           function = new FunctionAdd();           operandA = operandAccumilator;            operandAccumilator.clear();        } }); JButton buttonSubtract = new JButton(new AbstractAction(-){    public void actionPerformed(ActionEvent e) {           function = new FunctionSubtract();           operandA = operandAccumilator;            operandAccumilator.clear();        } });// same for other functionsObviosly this leads to some code duplication, so we extract the parts that change to local variables: String operator = +; CalculatorFunction buttonFunction =  new FunctionAdd(); JButton buttonAdd = new JButton(new AbstractAction(operator){    public void actionPerformed(ActionEvent e) {           function = buttonFunction;           operandA = operandAccumilator;            operandAccumilator.clear();        } }); operator = -; buttonFunction =  new FunctionSubtract(); JButton buttonAdd = new JButton(new AbstractAction(operator){    public void actionPerformed(ActionEvent e) {           function = buttonFunction;           operandA = operandAccumilator;            operandAccumilator.clear();        } });// same for other functionsnow we can extract the identical repeated code into a parameterized method:private JButton configureButton(String operator, CalculatorFunction buttonFunction){ return new JButton(new AbstractAction(operator){    public void actionPerformed(ActionEvent e) {           function = buttonFunction;           operandA = operandAccumilator;            operandAccumilator.clear();        }   }); }and use that in the gui setup:JButton buttonAdd = configureButton(+, new FunctionAdd());JButton buttonSubtract = configureButton(-, new FunctionSubtract());// same for other functionsIn consequence the method calculate change to:   try {        float x = Float.parseFloat(number[0]);        float y = Float.parseFloat(number[1]);                    screen.setText(String.valueOf(function.caculate(x,y)));    } catch (Exception e){        screen.setText(Please enter numbers);    }That's all, no more code in calculate ...whats operandA and OperandAccumilator I can't find it any where in your code  user7639356These are (new) member variables. The Number buttons are expected to add individual digits to operandAccumilator. if I use keyboard then it wouldn't work, though.  user7639356Neither would have your original code.Either way you have to convert the user input (given by GUI or command line) into model data. Usually it is easier to do with an OO approach than with the procedural solution you came up with.