import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Stack;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField inputField; // 显示输入和输出的文本框
private JButton button1, button2, button3, button4, button5;
private JButton button6, button7, button8, button9, button0;
private JButton buttonAdd, buttonSub, buttonMul, buttonDiv;
private JButton buttonSqrt, buttonFactorial, buttonClear, buttonEqual;
private StringBuilder input = new StringBuilder(); // 计算器输入的内容
public Calculator() {
super("Calculator"); // 设置标题
Container container = getContentPane();
container.setLayout(new BorderLayout()); // 设置布局管理器
// 初始化组件
inputField = new JTextField();
inputField.setEditable(false);
inputField.setHorizontalAlignment(JTextField.RIGHT);
container.add(inputField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
button7 = new JButton("7");
button7.addActionListener(this);
buttonPanel.add(button7);
button8 = new JButton("8");
button8.addActionListener(this);
buttonPanel.add(button8);
button9 = new JButton("9");
button9.addActionListener(this);
buttonPanel.add(button9);
buttonDiv = new JButton("/");
buttonDiv.addActionListener(this);
buttonPanel.add(buttonDiv);
button4 = new JButton("4");
button4.addActionListener(this);
buttonPanel.add(button4);
button5 = new JButton("5");
button5.addActionListener(this);
buttonPanel.add(button5);
button6 = new JButton("6");
button6.addActionListener(this);
buttonPanel.add(button6);
buttonMul = new JButton("*");
buttonMul.addActionListener(this);
buttonPanel.add(buttonMul);
button1 = new JButton("1");
button1.addActionListener(this);
buttonPanel.add(button1);
button2 = new JButton("2");
button2.addActionListener(this);
buttonPanel.add(button2);
button3 = new JButton("3");
button3.addActionListener(this);
buttonPanel.add(button3);
buttonSub = new JButton("-");
buttonSub.addActionListener(this);
buttonPanel.add(buttonSub);
button0 = new JButton("0");
button0.addActionListener(this);
buttonPanel.add(button0);
buttonClear = new JButton("C");
buttonClear.addActionListener(this);
buttonPanel.add(buttonClear);
buttonEqual = new JButton("=");
buttonEqual.addActionListener(this);
buttonPanel.add(buttonEqual);
buttonAdd = new JButton("+");
buttonAdd.addActionListener(this);
buttonPanel.add(buttonAdd);
container.add(buttonPanel, BorderLayout.CENTER);
setSize(280, 210); // 设置窗口尺寸
setLocation(500, 100); // 设置窗口位置
setResizable(true); // 禁止窗口大小调整
setVisible(true); // 显示窗口
}
// 处理按钮的点击事件
@Override
public void actionPerformed(ActionEvent e) {
String text = e.getActionCommand();
char ch = text.charAt(0);
if (ch >= '0' && ch <= '9') { // 数字键
input.append(ch);
} else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/")) { // 运算符键
input.append(" " + ch + " ");
} else if (text.equals("C")) { // 清除键
input.setLength(0);
} else if (text.equals("=")) { // 计算结果
try {
String inputStr = input.toString();
double result = evaluate(inputStr);
inputField.setText(formatResult(result));
input.setLength(0);
input.append(formatResult(result));
} catch (Exception ex) {
inputField.setText(ex.getMessage());
input.setLength(0);
}
}
inputField.setText(input.toString()); // 显示输入
}
// 计算表达式的值(逆波兰表达式算法)
private double evaluate(String inputStr) throws Exception {
String[] tokens = inputStr.split(" ");
Stack<Double> stack = new Stack<Double>();
for (String token : tokens) {
if (token.isEmpty()) {
continue;
}
char ch = token.charAt(0);
if (ch >= '0' && ch <= '9') { // 数字
double num = Double.parseDouble(token);
stack.push(num);
} else if (token.length() == 1 && "+-*/".indexOf(ch) >= 0) { // 运算符
if (stack.size() < 2) {
throw new Exception("Invalid input");
}
double b = stack.pop();
double a = stack.pop();
switch (ch) {
case '+':
stack.push(a + b);
break;
case '-':
stack.push(a - b);
break;
case '*':
stack.push(a * b);
break;
case '/':
if (b == 0) {
throw new Exception("Division by zero");
}
stack.push(a / b);
break;
}
} else {
throw new Exception("Invalid input");
}
}
if (stack.isEmpty()) {
throw new Exception("Empty input");
}
double result = stack.pop();
if (!stack.isEmpty()) {
throw new Exception("Invalid input");
}
return result;
}
// 格式化结果字符串
private String formatResult(double result) {
if (Double.isNaN(result) || Double.isInfinite(result)) {
return "Error";
} else if (result == (int) result) {
return String.format("%d", (int) result);
} else {
return String.format("%.2f", result);
}
}
}