java简易计算器课设
时间: 2023-12-20 13:32:53 浏览: 176
java课程设计 简易计算器
5星 · 资源好评率100%
以下是一个简易的Java计算器程序的示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 char operator;
public Calculator() {
setTitle("简易计算器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textField = new JTextField();
textField.setHorizontalAlignment(JTextField.RIGHT);
add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.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);
buttonPanel.add(buttons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.matches("[0-9.]")) {
textField.setText(textField.getText() + command);
} else if (command.matches("[/*\\-+]")) {
num1 = Double.parseDouble(textField.getText());
operator = command.charAt(0);
textField.setText("");
} else if (command.equals("=")) {
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case '/':
result = num1 / num2;
break;
case '*':
result = num1 * num2;
break;
case '-':
result = num1 - num2;
break;
case '+':
result = num1 + num2;
break;
}
textField.setText(String.valueOf(result));
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个程序使用了Java Swing库来创建一个简易的计算器界面。用户可以通过鼠标或键盘输入数字和运算符,然后计算器会显示结果。
阅读全文