简单的java计算代码无法完全运行

时间:2021-06-22 16:50:11

I have been creating a calculator as a beginner in Java. I have added in buttons that have a more complex functionality, and for some reason they just don't work.

我一直在用Java创建一个计算器作为初学者。我添加了具有更复杂功能的按钮,并且由于某种原因它们只是不起作用。

Can somebody please educate me on why these java calculations are not working properly? The buttons that work fine are the plus, minus, multiply and divide. The buttons that aren't working so well are the percentage, squareRt, and the PlusMinus buttons.

有人可以告诉我为什么这些java计算不能正常工作吗?工作正常的按钮是加号,减号,乘法和除法。不能正常工作的按钮是百分比,squareRt和PlusMinus按钮。

You can see in the calculator engine that I have implemented the correct method of calculation, however when the problematic buttons are pressed, the text display area of the calculator goes blank, when for example, if you press in 64 on the calculator and then press sqrt, it is suppose to display the Square root of 64, but is not doing so. Thanks for any help in advance. (take it easy on me i'm a beginner)

您可以在计算器引擎中看到我已经实现了正确的计算方法,但是当按下有问题的按钮时,计算器的文本显示区域变为空白,例如,如果您在计算器上按64然后按sqrt,假设显示64的平方根,但是没有这样做。在此先感谢您的帮助。 (放轻松,我是初学者)

Here is the calculator

这是计算器

package Calculator;

import javax.swing.*;

import java.awt.GridLayout;
import java.awt.BorderLayout;

public class Calculator {

// Declare and instantiate window components
JButton button0 = new JButton("0");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton buttonPoint = new JButton(".");
JButton buttonEqual = new JButton("=");
JButton buttonPlus = new JButton("+");
JButton buttonMinus = new JButton("-");
JButton buttonDivide = new JButton("/");
JButton buttonMultiply = new JButton("*");
JButton buttonSquareRt = new JButton("sqrt");
JButton buttonPercentage = new JButton("%");
JButton buttonPlusMinus = new JButton("+/-");
JButton buttonClear = new JButton("C");


JPanel windowContent = new JPanel();
JTextField displayField = new JTextField(30);

// Constructor
Calculator() {

    // Set the layout manager for this panel

    BorderLayout bl = new BorderLayout();
    windowContent.setLayout(bl);

    // Add the display field to the top of the window

    windowContent.add("North", displayField);

    // Create the panel with the GridLayout
    // that will contain 12 buttons - 10 numeric ones, and
    // buttons with the point and the equal sign

    JPanel p1 = new JPanel();
    GridLayout gl = new GridLayout(4, 3);
    p1.setLayout(gl);

    p1.add(button1);
    p1.add(button2);
    p1.add(button3);
    p1.add(button4);
    p1.add(button5);
    p1.add(button6);
    p1.add(button7);
    p1.add(button8);
    p1.add(button9);
    p1.add(button0);
    p1.add(buttonPoint);
    p1.add(buttonEqual);

    // Add the panel p1 to the centre area of the window
    windowContent.add("Center", p1);

    // Create the panel with the GridLayout
    // that will contain 4 action buttons -
    // Plus, Minus, Divide and Multiply

    JPanel p2 = new JPanel();
    GridLayout gl2 = new GridLayout(4, 1);
    p2.setLayout(gl);
    p2.add(buttonPlus);
    p2.add(buttonMinus);
    p2.add(buttonMultiply);
    p2.add(buttonDivide);

    //adding the task buttons to go on extra column
    p2.add(buttonSquareRt);
    p2.add(buttonPercentage);
    p2.add(buttonPlusMinus);
    p2.add(buttonClear);

    // Add the panel p2 to the east area of the window
    windowContent.add("East", p2);


    // Create the frame and add the content pane to it
    JFrame frame = new JFrame("Calculator");

    frame.setContentPane(windowContent);

    // set the size of the window to be big enough to
    // accommodate all window controls

    frame.pack();

    // Display the window
    frame.setVisible(true);
    // Instantiate the event listener and

    // register each button with it

    CalculatorEngine calcEngine = new CalculatorEngine(this);

    button0.addActionListener(calcEngine);
    button1.addActionListener(calcEngine);
    button2.addActionListener(calcEngine);
    button3.addActionListener(calcEngine);
    button4.addActionListener(calcEngine);
    button5.addActionListener(calcEngine);
    button6.addActionListener(calcEngine);
    button7.addActionListener(calcEngine);
    button8.addActionListener(calcEngine);
    button9.addActionListener(calcEngine);
    buttonPoint.addActionListener(calcEngine);
    buttonPlus.addActionListener(calcEngine);
    buttonMinus.addActionListener(calcEngine);
    buttonDivide.addActionListener(calcEngine);
    buttonMultiply.addActionListener(calcEngine);
    buttonEqual.addActionListener(calcEngine);
    buttonSquareRt.addActionListener(calcEngine);
    buttonPercentage.addActionListener(calcEngine);
    buttonPlusMinus.addActionListener(calcEngine);
    buttonClear.addActionListener(calcEngine);

}

public static void main(String[] args) {
    // Instantiate the class Calculator
    Calculator calc = new Calculator();
}
}

And here is the engine with the problematic code package Calculator;

这里是带有问题代码包计算器的引擎;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;

public class CalculatorEngine implements ActionListener {

Calculator parent; // a reference to Calculator window
char selectedAction = ' '; // +, -, /, or *

double currentResult = 0;

// Constructor stores the reference to the Calculator
// window in the member variable parent
CalculatorEngine(Calculator parent) {
    this.parent = parent;
}

public void actionPerformed(ActionEvent e) {

    // Get the source of this action
    JButton clickedButton = (JButton) e.getSource();
    String dispFieldText = parent.displayField.getText();
    double displayValue = 0;
    // Get the number from the text field
    // if it’s not empty
    if (!"".equals(dispFieldText)) {
        displayValue = Double.parseDouble(dispFieldText);
    }
    Object src = e.getSource();
    // For each action button memorize selected
    // action +, -, /, or *, store the current value
    // in the currentResult, and clean up the display
    // field for entering the next number

    if (src == parent.buttonPlus) {
        selectedAction = '+';
        currentResult = displayValue;
        parent.displayField.setText("");
    } else if (src == parent.buttonMinus) {
        selectedAction = '-';
        currentResult = displayValue;
        parent.displayField.setText("");
    } else if (src == parent.buttonDivide) {
        selectedAction = '/';
        currentResult = displayValue;
        parent.displayField.setText("");
    } else if (src == parent.buttonMultiply) {
        selectedAction = '*';
        currentResult = displayValue;
        parent.displayField.setText("");
    } else if (src == parent.buttonSquareRt) {
        selectedAction = 's';
        currentResult = displayValue;
        parent.displayField.setText("");
    } else if (src == parent.buttonPercentage){
        selectedAction = 'p';
        currentResult = displayValue;
        parent.displayField.setText("");
    } else if (src == parent.buttonPlusMinus){
        selectedAction = 'm';
        currentResult = displayValue;
        parent.displayField.setText("");
    }

    else if (src == parent.buttonEqual) {
        // Perform the calculations based on selectedAction
        // update the value of the variable currentResult
        // and display the result
        if (selectedAction == '+') {
            currentResult += displayValue;
            // Convert the result to String by concatenating
            // to an empty string and display it
            parent.displayField.setText("" + currentResult);
        } else if (selectedAction == '-') {
            currentResult -= displayValue;
            parent.displayField.setText("" + currentResult);
        } else if (selectedAction == '/') {
            currentResult /= displayValue;
            parent.displayField.setText("" + currentResult);
        } else if (selectedAction == '*') {
            currentResult *= displayValue;
            parent.displayField.setText("" + currentResult);
        } else if (selectedAction == 's') {
            currentResult = Math.sqrt(displayValue);
            parent.displayField.setText("" + currentResult);
        } else if (selectedAction == 'p') {
            currentResult = currentResult / 100;
            parent.displayField.setText("" + currentResult);
        } else if (selectedAction == 'm') {
            displayValue = currentResult * -1;
            parent.displayField.setText("" + currentResult);
        }

    } else {
        // For all numeric buttons append the button's
        // label to the text field
        String clickedButtonLabel = clickedButton.getText();
        parent.displayField.setText(dispFieldText + clickedButtonLabel);
    }
  }
}

1 个解决方案

#1


1  

It appears that this code would work as expected where you would type a number like 64, then you would press the square root button - which would clear the displayField - then you would press the equals button, and it would display the result.

看起来这个代码可以按预期工作,你可以输入一个像64这样的数字,然后按平方根按钮 - 这将清除displayField - 然后你按下等于按钮,它会显示结果。

If you want to make it more obvious that you should be pressing the equals button to get the result, you might want to echo the users entry surrounded by text that represents the function to be performed, for example:

如果您想更明显地应该按下等于按钮来获得结果,您可能希望回显用于表示要执行的函数的文本所包围的用户条目,例如:

else if (src == parent.buttonSquareRt) {
    selectedAction = 's';
    currentResult = displayValue;
    parent.displayField.setText("sqrt(" + currentResult + ")");
}

#1


1  

It appears that this code would work as expected where you would type a number like 64, then you would press the square root button - which would clear the displayField - then you would press the equals button, and it would display the result.

看起来这个代码可以按预期工作,你可以输入一个像64这样的数字,然后按平方根按钮 - 这将清除displayField - 然后你按下等于按钮,它会显示结果。

If you want to make it more obvious that you should be pressing the equals button to get the result, you might want to echo the users entry surrounded by text that represents the function to be performed, for example:

如果您想更明显地应该按下等于按钮来获得结果,您可能希望回显用于表示要执行的函数的文本所包围的用户条目,例如:

else if (src == parent.buttonSquareRt) {
    selectedAction = 's';
    currentResult = displayValue;
    parent.displayField.setText("sqrt(" + currentResult + ")");
}