我的计算器无法正确计算 java

My calculator cannot calculate properly java

大家好,我是一名年轻的程序员,我的计算器需要一些帮助。每次我尝试计算它时,它总是给我错误的答案,例如 2+2 等于 -2。有人可以帮帮我吗。顺便说一句,我正在从一本书中学习代码,所以有人可能会认出其中的一些代码。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class CalculationEngine implements ActionListener{

String number1, number2, abplus,abminus,abEquals1;
double a,b,a2,b2;
int rounding,rounding2;


//Don't change this!
Calculator c2;
//Or this.
CalculationEngine(Calculator c2){
    //This statement allows this class to "communicate" with the other class
    this.c2=c2;
}

@Override
public void actionPerformed(ActionEvent e) {

    JButton getbutton=(JButton) e.getSource();

    String getbuttonlabel= getbutton.getText();
    String buttonsfieldtext=c2.getbuttonsfield();

    c2.setbuttonsfieldtext(buttonsfieldtext+getbuttonlabel);

    number1=buttonsfieldtext;
    number2=buttonsfieldtext;

    try{
        if(getbuttonlabel.equals("+")){
            a=Double.parseDouble(number1);
            c2.setbuttonsfieldtext("");
        }else if (getbuttonlabel.equals("=")){
            b=Double.parseDouble(number2);
            rounding= (int) Math.round(a+b);
            abplus=String.valueOf(rounding);
            c2.setbuttonsfieldtext(abplus);

        }

    }catch(NumberFormatException e1){
        System.out.println("There was an error in your typing "+e1.getMessage());
        c2.setbuttonsfieldtext("");
    }

    try{
        if(getbuttonlabel.equals("-")){
            String number3=buttonsfieldtext;
            a2=Double.parseDouble(number3);
            c2.setbuttonsfieldtext("");
        }else if (getbuttonlabel.equals("=")){
            String number4=buttonsfieldtext;
            b2=Double.parseDouble(number4);
            rounding2= (int) Math.round(a2-b2);
            abminus=String.valueOf(rounding2);
            c2.setbuttonsfieldtext(abminus);

        }

    }catch(NumberFormatException e1){
        System.out.println("There was an error in your typing "+e1.getMessage());
        c2.setbuttonsfieldtext("");
    }




}

}

在这一行,

int rounding= (int) Math.round(a+b);

在设置新的 a 和 b 值之前,您正在设置舍入值。您需要在设置新的 a 和 b 值后 调用此方法,否则舍入值将无法正确更新。

您还有两个块开始:else if (getbuttonlabel.equals("="))这两个 每次 getbuttonlabel 等于“=”时都会执行这些块,因此如果您尝试将两个数字相加,第二个块将始终覆盖第一个的结果,因此发生的情况是,两个数字在第一个块中相加,然后在第二个“=”块中,从第一个数字中减去两个数字的总和,结果是第二个数字的负值。

要在不完全改变程序设计的情况下解决这个问题,您可以在 class(不是函数)中添加一个变量来存储最后一个操作是 + 还是 -。然后在函数中,在处理“=”块之前检查它。这样只有正确的“=”块才会在调用函数时得到 运行。