3.编写程序实现一个简单计算器的基本功能,具体可以模仿Windows附件中的计算器或模拟常见的实物计算器。使用java
时间: 2023-06-18 21:06:25 浏览: 180
用java编写的计算器 基本功能可以实现.doc
以下是一个简单的基于Java Swing的计算器程序实现:
```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 JPanel panel;
private JButton[] buttons;
private JTextField display;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
private double result = 0;
private String operator = "";
private boolean start = true;
public Calculator() {
super("Calculator");
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
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]);
}
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
getContentPane().add(display, BorderLayout.NORTH);
getContentPane().add(panel, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.matches("[0-9\\.]")) {
if (start) {
display.setText(command);
start = false;
} else {
display.setText(display.getText() + command);
}
} else if (command.matches("[+\\-*/=]")) {
if (operator.equals("")) {
result = Double.parseDouble(display.getText());
} else if (operator.equals("+")) {
result += Double.parseDouble(display.getText());
} else if (operator.equals("-")) {
result -= Double.parseDouble(display.getText());
} else if (operator.equals("*")) {
result *= Double.parseDouble(display.getText());
} else if (operator.equals("/")) {
result /= Double.parseDouble(display.getText());
}
display.setText("" + result);
operator = command;
start = true;
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
该程序使用GridLayout布局管理器来排列按钮,并实现了ActionListener接口以处理按钮点击事件。在actionPerformed方法中,程序先判断点击的按钮是数字还是运算符,然后根据不同的运算符来计算结果,并将结果显示在文本框中。
阅读全文