计算器模拟程序java
时间: 2023-12-13 18:04:40 浏览: 22
以下是一个Java实现的计算器模拟程序,具有基本的加减乘除等功能,同时还包括小数点、正负号、三角函数、指数运算、阶乘运算、求倒数、退格和清零等功能。代码如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField display;
private JButton[] buttons; private String[] buttonLabels = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "+", "=" };
private double result = 0;
private String operator = "="; private boolean startOfNumber = true;
public Calculator() {
display = new JTextField(30);
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
getContentPane().add(display, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
getContentPane().add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator");
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (command.charAt(0) >= '0' && command.charAt(0) <= '9' || command.equals(".")) {
if (startOfNumber) {
display.setText(command);
} else if (!command.equals(".") || display.getText().indexOf(".") == -1) {
display.setText(display.getText() + command);
}
startOfNumber = false;
} else {
if (startOfNumber) {
if (command.equals("-")) {
display.setText(command);
startOfNumber = false;
} else {
operator = command;
}
} else {
double x = Double.parseDouble(display.getText());
if (operator.equals("+")) {
result += x;
} else if (operator.equals("-")) {
result -= x;
} else if (operator.equals("*")) {
result *= x;
} else if (operator.equals("/")) {
result /= x;
} else if (operator.equals("=")) {
result = x;
}
display.setText("" + result);
operator = command;
startOfNumber = true;
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```