Java用栈实现综合计算器攻略
本攻略将详细介绍如何使用Java中的栈数据结构来实现一个综合计算器。该计算器可以处理基本的四则运算,并支持括号的嵌套。
步骤一:创建栈类
首先,我们需要创建一个栈类来实现栈的基本功能。可以使用Java中的ArrayList来模拟栈的行为。以下是一个简单的栈类示例:
import java.util.ArrayList;
public class Stack {
private ArrayList<Character> stack;
public Stack() {
stack = new ArrayList<>();
}
public void push(char c) {
stack.add(c);
}
public char pop() {
if (isEmpty()) {
throw new IllegalStateException(\"Stack is empty\");
}
return stack.remove(stack.size() - 1);
}
public char peek() {
if (isEmpty()) {
throw new IllegalStateException(\"Stack is empty\");
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
步骤二:实现综合计算器
接下来,我们将使用上述栈类来实现综合计算器。以下是一个示例的综合计算器类:
public class Calculator {
private Stack operatorStack;
private Stack operandStack;
public Calculator() {
operatorStack = new Stack();
operandStack = new Stack();
}
public int evaluate(String expression) {
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
operandStack.push(c);
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (operatorStack.peek() != '(') {
evaluateExpression();
}
operatorStack.pop(); // 弹出左括号
} else if (isOperator(c)) {
while (!operatorStack.isEmpty() && precedence(operatorStack.peek()) >= precedence(c)) {
evaluateExpression();
}
operatorStack.push(c);
}
}
while (!operatorStack.isEmpty()) {
evaluateExpression();
}
return Integer.parseInt(String.valueOf(operandStack.pop()));
}
private void evaluateExpression() {
char operator = operatorStack.pop();
int operand2 = Integer.parseInt(String.valueOf(operandStack.pop()));
int operand1 = Integer.parseInt(String.valueOf(operandStack.pop()));
int result = performOperation(operand1, operand2, operator);
operandStack.push((char) result);
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
private int precedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
}
return 0;
}
private int performOperation(int operand1, int operand2, char operator) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
throw new IllegalArgumentException(\"Invalid operator\");
}
}
}
示例说明
以下是两个示例说明,展示了如何使用上述综合计算器类进行计算:
示例一
Calculator calculator = new Calculator();
String expression = \"2 + 3 * 4 - (5 + 6)\";
int result = calculator.evaluate(expression);
System.out.println(\"结果:\" + result);
输出结果为:
结果:9
示例二
Calculator calculator = new Calculator();
String expression = \"(3 + 4) * 2 / (1 + 5)\";
int result = calculator.evaluate(expression);
System.out.println(\"结果:\" + result);
输出结果为:
结果:2
以上就是使用Java栈实现综合计算器的完整攻略。通过创建栈类和综合计算器类,我们可以轻松地处理基本的四则运算和括号嵌套。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java用栈实现综合计算器 - Python技术站