You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
4.7 KiB

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class calculator extends JFrame implements ActionListener {
private JTextField display;
private String equation = "";
private boolean newNumber = true;
public calculator() {
setTitle("简易计算器");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
display = new JTextField("0");
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(new Font("Arial", Font.BOLD, 24));
display.setPreferredSize(new Dimension(300, 60));
add(display, BorderLayout.NORTH);
JPanel panel = new JPanel();
1 month ago
panel.setLayout(new GridLayout(5, 4));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
1 month ago
"C", "%" // 添加取余按钮
};
for (String label : buttons) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.BOLD, 18));
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
1 month ago
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".indexOf(command) >= 0) {
if (newNumber) {
display.setText(command);
newNumber = false;
} else {
display.setText(display.getText() + command);
}
1 month ago
} else if ("+-*/%".indexOf(command) >= 0) { // 添加 % 运算符
equation = display.getText() + command;
display.setText("0");
newNumber = true;
} else if (command.equals("=")) {
try {
equation += display.getText();
1 month ago
double result = new ExpressionEvaluator(equation).evaluate();
if (result == (long) result) {
display.setText(String.valueOf((long) result));
} else {
display.setText(String.valueOf(result));
2 months ago
}
newNumber = true;
} catch (Exception ex) {
display.setText("Error");
}
} else if (command.equals("C")) {
display.setText("0");
equation = "";
newNumber = true;
2 months ago
}
}
1 month ago
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
calculator calc = new calculator();
calc.setVisible(true);
});
}
}
1 month ago
class ExpressionEvaluator {
private int pos = -1;
private int ch;
private final String str;
1 month ago
public ExpressionEvaluator(String str) {
this.str = str;
}
1 month ago
private void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}
1 month ago
private boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
1 month ago
public double evaluate() {
nextChar();
double x = parseExpression();
if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
return x;
}
1 month ago
private double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // addition
else if (eat('-')) x -= parseTerm(); // subtraction
else return x;
}
}
1 month ago
private double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor(); // multiplication
else if (eat('/')) x /= parseFactor(); // division
else if (eat('%')) x %= parseFactor(); // modulus
else return x;
}
}
1 month ago
private double parseFactor() {
if (eat('+')) return parseFactor(); // unary plus
if (eat('-')) return -parseFactor(); // unary minus
double x;
int startPos = this.pos;
if (eat('(')) { // parentheses
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(str.substring(startPos, this.pos));
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
}
if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation
return x;
2 months ago
}
}