Q:

Trying to build a calculator in java GUI

In here im just trying to add first numbers to the second numbers when (=) button is pressed. this code shows only the second number on the screen when (=) button is pressed. once this works i want it to work with different arithmetic operator buttons e.g (+ - * /). please help if you can figure out my code.
private class TheHandler implements ActionListener{
    public void actionPerformed(ActionEvent e) {

        //add values to buttons
        String num = "";
        if(e.getSource()==btn[0]){
            num = "7";
        }else if(e.getSource()==btn[1]){
            num = "8";
        }else if(e.getSource()==btn[2]){
            num = "9";
        }else if(e.getSource()==btn[5]){
            num = "4";
        }else if(e.getSource()==btn[6]){
            num = "5";
        }else if(e.getSource()==btn[7]){
            num = "6";
        }else if(e.getSource()==btn[10]){
            num = "1";
        }else if(e.getSource()==btn[11]){
            num = "2";
        }else if(e.getSource()==btn[12]){
            num = "3";
        }else if(e.getSource()==btn[15]){               
            num = "0";
        }

        //set the values to the text field          
        if (tDisplay.getText().equals("0"))
            tDisplay.setText(num);
        else
            tDisplay.setText(tDisplay.getText()+num);

        //temporary values to be stored when arithmetic operators are pressed
        double tempValue =0;
        double tempValue2 =0;
        double equalsTo=0;

        //if = button is pressed
        if(e.getSource()==btn[19]){
            tempValue2 = Double.parseDouble(tDisplay.getText());
            equalsTo = tempValue+tempValue2;
            tDisplay.setText(String.valueOf(equalsTo));
        }

        //if + button is pressed
        if(e.getSource()==btn[3]){
            tempValue = Double.parseDouble(tDisplay.getText());
            tDisplay.setText("");
        }

    }

}

A:

Looks like you have declared local variables to store your intermediate results, so these variables are reinitialized to 0 each time your action is performed. Instead, you might want them to be class properties, so the values in variables can "survive" several calls to actionPerformed method.

