用 JAVA 编写一个计算器,能实现四则混合运算并且带有括号功能,计算器有图形化界面,能对异常进行处理,并且检验输入的合法性,对不合法的输入给出具体的提示信息。
时间: 2024-05-23 10:04:56 浏览: 109
这是一个比较复杂的项目,需要使用 Java GUI 库来实现图形化界面,同时需要编写适当的算法来解析输入的表达式并进行计算。以下是一个简单的示例程序,可能需要根据具体需求进行修改和完善。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField inputField;
private JButton[] buttons;
private String[] buttonText = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "(", "0", ")", "/", "C", "=", "."};
private String inputText = "";
public Calculator() {
setTitle("Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 创建输入框和按钮
inputField = new JTextField();
inputField.setEditable(false);
inputField.setHorizontalAlignment(JTextField.RIGHT);
add(inputField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttons = new JButton[buttonText.length];
for (int i = 0; i < buttonText.length; i++) {
buttons[i] = new JButton(buttonText[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("C")) {
inputText = "";
inputField.setText("");
} else if (command.equals("=")) {
try {
double result = evaluate(inputText);
inputText = Double.toString(result);
inputField.setText(inputText);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
} else {
inputText += command;
inputField.setText(inputText);
}
}
private double evaluate(String expression) throws IllegalArgumentException {
// 检查输入是否合法
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (!Character.isDigit(ch) && ch != '.' && ch != '+' && ch != '-' && ch != '*' && ch != '/' && ch != '(' && ch != ')') {
throw new IllegalArgumentException("Invalid character: " + ch);
}
}
int leftParentheses = 0, rightParentheses = 0;
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (ch == '(') {
leftParentheses++;
} else if (ch == ')') {
rightParentheses++;
if (rightParentheses > leftParentheses) {
throw new IllegalArgumentException("Unmatched right parenthesis");
}
}
}
if (leftParentheses != rightParentheses) {
throw new IllegalArgumentException("Unmatched parentheses");
}
// 使用栈来解析表达式
Stack<Double> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
int i = 0;
while (i < expression.length()) {
char ch = expression.charAt(i);
if (Character.isDigit(ch) || ch == '.') {
int j = i;
while (j < expression.length() && (Character.isDigit(expression.charAt(j)) || expression.charAt(j) == '.')) {
j++;
}
double operand = Double.parseDouble(expression.substring(i, j));
operands.push(operand);
i = j;
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(ch)) {
char operator = operators.pop();
double operand2 = operands.pop();
double operand1 = operands.pop();
double result = applyOperator(operator, operand1, operand2);
operands.push(result);
}
operators.push(ch);
i++;
} else if (ch == '(') {
operators.push(ch);
i++;
} else if (ch == ')') {
while (operators.peek() != '(') {
char operator = operators.pop();
double operand2 = operands.pop();
double operand1 = operands.pop();
double result = applyOperator(operator, operand1, operand2);
operands.push(result);
}
operators.pop();
i++;
} else {
i++;
}
}
while (!operators.isEmpty()) {
char operator = operators.pop();
double operand2 = operands.pop();
double operand1 = operands.pop();
double result = applyOperator(operator, operand1, operand2);
operands.push(result);
}
return operands.pop();
}
private int precedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
} else {
return 0;
}
}
private double applyOperator(char operator, double operand1, double operand2) {
switch (operator) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
default: return 0;
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
阅读全文