0
Follow
2
View

Java Scientific calculator GUI

diaorong55 注册会员
2023-01-25 01:55

I don't fully understand the purpose of all fields in your class, so I'll propose my own set. If we (ab)use the text field as storage for the current value, two state fields are enough for the basic functionality. It's not necessary to store any more data:

private String firstBinaryOperand = null;
private char binaryOp = ' ';

These fields are used if there is a pending binary operation such as + or -. We don't need them for unary operations. For example, if the user types "700 + 200 =", then

  • When the "+" button is pressed for the first time, the currently displayed value (700) is stored in firstBinaryOperand and '+' in binaryOp.
  • When the "=" button is pressed, the current value (200) and the value cached in firstBinaryOperand are added and the result (900) written into the text field.

We therefore need a method that evaluates a pending binary operation if there is one and writes the result into the text field:

// Evaluate pending binary operation, if there is one.
private void evaluateBinaryOp() {
    if (binaryOp != ' ') {
        double firstOperand = Double.parseDouble(firstBinaryOperand);
        double secondOperand = Double.parseDouble(field.getText());

        double result;
        if (binaryOp == '+') {
            field.setText(Double.toString(firstOperand + secondOperand));
        } else if (binaryOp == '-') {
            field.setText(Double.toString(firstOperand - secondOperand));
        }
        // Implementation of further binary operands ...

        // Update state, there is no longer a pending binary operation
        firstBinaryOperand = null;
        binaryOp = ' ';
    }
}

Addition as an example of a binary operation:

if (e.getSource() == add){
    evaluateBinaryOp(); // evaluate pending binary op, if any
    firstBinaryOperand = field.getText(); 
    binaryOp = '+'; 
    field.setText("0"); 
}

Unary operations are simpler, but we still have to check whether there is a pending binary operation and evaluate it first if this is the case:

if (e.getSource() == oneOverX) {
    evaluateBinaryOp(); // evaluate pending binary op, if any
    double currentValue = Double.parseDouble(field.getText()); 
    field.setText(Double.toString(1.0 / currentValue)); 
}

All other unary and binary operations can be implemented using the same pattern.

This is going to give you a very basic calculator whose behavior differs a bit from the usual. For example, if the user presses +, they will not see the intermediate result but always 0. The intermediate result isn't lost though as it is stored in the firrstBinaryOperand field in the background. The correct result will be shown once = or another unary operator is used. I hope this answers your question and is enough to get you started, you can then refine the behavior in a second step.