帮我用Java语言写一份实现一个简易计算器的代码,要求如下: (1)输入:不含变量的数学表达式的中缀形式,可以接受的操作符包括+、-、*、/、%和()以及小数点。 (2)输出:如果表达式正确,则输出表达式的结果,如果表达式非法,则输出错误信息。 (3)能够正确运算带括号的数学表达式的中缀形式。 (4)可以借助栈来实现,使用图形用户界面。
时间: 2023-12-23 19:03:26 浏览: 65
基于java实现简单计算器
以下是一个简单的Java代码实现一个基础计算器,支持加、减、乘、除、取模和括号运算:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField displayTextField;
public Calculator() {
super("简易计算器");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
displayTextField = new JTextField();
displayTextField.setEditable(false);
mainPanel.add(displayTextField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
for (int i = 0; i < buttonLabels.length; i++) {
JButton button = new JButton(buttonLabels[i]);
button.addActionListener(this);
buttonPanel.add(button);
}
mainPanel.add(buttonPanel, BorderLayout.CENTER);
setContentPane(mainPanel);
}
private String calculate(String expression) {
// Check if expression is null or empty
if (expression == null || expression.isEmpty()) {
return "错误:表达式为空";
}
// Check if expression contains only valid characters
if (!expression.matches("[0-9+\\-*/%.()]+")) {
return "错误:表达式包含无效字符";
}
// Check if expression has balanced parentheses
int parenthesesCount = 0;
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (c == '(') {
parenthesesCount++;
} else if (c == ')') {
parenthesesCount--;
}
if (parenthesesCount < 0) {
return "错误:表达式包含未匹配的右括号";
}
}
if (parenthesesCount > 0) {
return "错误:表达式包含未匹配的左括号";
}
// Evaluate expression
try {
double result = evaluate(expression);
return Double.toString(result);
} catch (IllegalArgumentException e) {
return "错误:" + e.getMessage();
}
}
private double evaluate(String expression) {
Stack<Double> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
int i = 0;
while (i < expression.length()) {
char c = expression.charAt(i);
if (Character.isDigit(c) || c == '.') {
StringBuilder operandBuilder = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
operandBuilder.append(expression.charAt(i));
i++;
}
double operand = Double.parseDouble(operandBuilder.toString());
operands.push(operand);
} else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '%') {
while (!operators.isEmpty() && hasHigherOrEqualPrecedence(c, operators.peek())) {
evaluateTop(operands, operators);
}
operators.push(c);
i++;
} else if (c == '(') {
operators.push(c);
i++;
} else if (c == ')') {
while (!operators.isEmpty() && operators.peek() != '(') {
evaluateTop(operands, operators);
}
if (operators.isEmpty()) {
throw new IllegalArgumentException("表达式包含未匹配的右括号");
}
operators.pop();
i++;
} else {
throw new IllegalArgumentException("表达式包含无效字符 " + c);
}
}
while (!operators.isEmpty()) {
evaluateTop(operands, operators);
}
if (operands.size() != 1 || !operators.isEmpty()) {
throw new IllegalArgumentException("表达式无效");
}
return operands.pop();
}
private boolean hasHigherOrEqualPrecedence(char operator1, char operator2) {
return (operator1 == '*' || operator1 == '/' || operator1 == '%') || (operator1 == '+' || operator1 == '-') && (operator2 == '+' || operator2 == '-');
}
private void evaluateTop(Stack<Double> operands, Stack<Character> operators) {
double operand2 = operands.pop();
double operand1 = operands.pop();
char operator = operators.pop();
double result = applyOperator(operator, operand1, operand2);
operands.push(result);
}
private double applyOperator(char operator, double operand1, double operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
if (operand2 == 0) {
throw new IllegalArgumentException("除数不能为零");
}
return operand1 / operand2;
case '%':
if (operand2 == 0) {
throw new IllegalArgumentException("除数不能为零");
}
return operand1 % operand2;
default:
throw new IllegalArgumentException("无效操作符 " + operator);
}
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
String expression = displayTextField.getText();
String result = calculate(expression);
displayTextField.setText(result);
} else {
displayTextField.setText(displayTextField.getText() + command);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setSize(300, 400);
calculator.setLocationRelativeTo(null);
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculator.setVisible(true);
}
}
```
该代码中使用了图形用户界面,包含数字、操作符和等号按钮,以及一个文本框来显示表达式和结果。当用户点击等号按钮时,程序会调用 `calculate` 方法来计算表达式的值,然后将结果显示在文本框中。 `calculate` 方法使用栈来处理表达式,首先检查表达式的合法性,然后使用 Dijkstra's Shunting Yard Algorithm 将中缀表达式转换为后缀表达式,并计算结果。
阅读全文