java计算器如何实现运算_java 编写计算器 怎样实现连续运算?
时间: 2023-12-08 12:06:23 浏览: 84
要实现一个简单的 Java 计算器,可以使用 Java Swing 来创建一个用户界面,并使用 Java 的算术运算符来执行基本的数学运算。下面是一个简单的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] buttons;
private String[] buttonLabels = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", ".", "=", "/"
};
private double num1, num2, result;
private String operator = "";
public Calculator() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
textField = new JTextField(15);
textField.setEditable(false);
panel.add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
panel.add(buttonPanel, BorderLayout.CENTER);
getContentPane().add(panel);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals("C")) {
textField.setText("");
} else if (label.equals("=")) {
num2 = Double.parseDouble(textField.getText());
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
textField.setText("" + result);
num1 = result;
operator = "";
} else if (label.equals("+") || label.equals("-") || label.equals("*") || label.equals("/")) {
num1 = Double.parseDouble(textField.getText());
operator = label;
textField.setText("");
} else {
textField.setText(textField.getText() + label);
}
}
}
```
这个计算器可以进行基本的加、减、乘、除运算。要实现连续运算,可以在等号按钮的事件处理程序中将运算结果存储到 num1 变量中,并清空操作符变量 operator,以便进行下一次运算。例如:
```java
else if (label.equals("=")) {
num2 = Double.parseDouble(textField.getText());
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
textField.setText("" + result);
num1 = result;
operator = "";
}
```
这样,用户就可以在计算器上进行连续的数学运算。
阅读全文