Java Netbeans Calculator执行错误的计算

时间:2017-10-20 06:27:47

标签: java calculator netbeans-8.2

我目前正在研究NetBeans中的GUI计算器。我的加法运算符运行良好,但对于我的减法,乘法和除法,它返回错误的值。我不认为我的逻辑计算有问题。

操作员返回的值:

减法: 输入值与负号的总和

乘法 0

0

以下是我的操作员按钮和功能:

// add button
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
    operator = "+";
    calculation(operator);
} 

// subtract button
private void btnSubtractActionPerformed(java.awt.event.ActionEvent evt) {                                            
    operator = "-";
    calculation(operator);
} 

// multiply button
private void btnMultiplyActionPerformed(java.awt.event.ActionEvent evt) {                                            
    operator = "*";
    calculation(operator);
}

// divide button
private void btnDivideActionPerformed(java.awt.event.ActionEvent evt) {                                          
    operator = "/";
    calculation(operator);
} 

// equals button
private void btnEqualsActionPerformed(java.awt.event.ActionEvent evt) {                                          
    calculation(operator);
    txtInput.setText(String.valueOf(accum2));
}


// calculation method
public void calculation(String operator){
    if(operator.equals("+")) {
        accum2 += accum1;
        accum1 = 0;
    } else if(operator.equals("-")){
        accum2 -= accum1;
        accum1 = 0;
    } else if(operator.equals("*")){
        accum2 *= accum1;
        accum1 = 0;
    } else if(operator.equals("/")){
        accum2 /= accum1;
        accum1 = 0;
    } else {
        accum2 = accum1;
        accum1 = 0;
    }
}

1 个答案:

答案 0 :(得分:0)

我认为在计算结果之前问题是accum2和accum2的值。因此,在执行计算之前,您可以使用System.out.println(" accum 1 "+ accum1)System.out.println(" accum 2 "+ accum2)来检查其值。