概述
package cn.zhouyu.test;
import java.util.Stack;
public class EvaluateExpression {
public static void main(String[] args) {
String expression = "(1+2)*4-3";
//1.1、创建一个存储操作数的栈
Stack<Integer> operandStack = new Stack<>();
//1.2、创建一个存储操作符和括号的栈
Stack<Character> operatorStack = new Stack<>();
//1.3、在expression的每个字符旁边插入空格,方便下面分割
expression = insertBlanks(expression);
//1.4、分割expression,得到单个的操纵数、操作符和括号
String[] tokens = expression.split(" ");
for(String token : tokens) {
//把分割后剩下的空格去掉
if(token.length() == 0) {
continue;
}
//2.1、如果是+或-操作符,处理在operatorStack栈顶的所有操作符。
else if(token.charAt(0) == '+' || token.charAt(0) == '-') {
while(!operatorStack.isEmpty() &&
(operatorStack.peek()== '+'||
operatorStack.peek()== '-'||
operatorStack.peek()== '*'||
operatorStack.peek()== '/')){
//计算operandStack中的两个数的加减乘除
processAnOperator(operandStack, operatorStack);
}
operatorStack.push(token.charAt(0));
}
//2.2、如果是*或/操作符,处理在operatorStack栈顶的所有*和/操作符
else if(token.charAt(0) == '*' || token.charAt(0) == '/') {
while(!operatorStack.isEmpty()&&
(operatorStack.peek()== '*'||
operatorStack.peek()== '/')) {
processAnOperator(operandStack, operatorStack);
}
operatorStack.push(token.charAt(0));
}
//2.3、如果是(,压入operatorStack
else if(token.charAt(0) == '(') {
operatorStack.push('(');
}
//2.4、如果是),重复处理来自operatorStack栈顶的操作符,直到看到栈上的(符号。
else if(token.charAt(0) == ')') {
while(operatorStack.peek()!='(') {
processAnOperator(operandStack,operatorStack);
}
operatorStack.pop();
}
else {
operandStack.push(new Integer(token));
}
}
//清除栈:重复处理来自operatorStack栈顶的操作符,直到operatorStack为空为主
while(!operatorStack.isEmpty()) {
processAnOperator(operandStack,operatorStack);
}
System.out.println(operandStack.pop());
}
private static String insertBlanks(String expression) {
String result = "";
for(int i=0;i<expression.length();i++) {
if(expression.charAt(i) == '(' || expression.charAt(i) == ')' ||
expression.charAt(i) == '+' || expression.charAt(i) == '-' ||
expression.charAt(i) == '*' || expression.charAt(i) == '/' ) {
result += " " + expression.charAt(i) + " ";
}else{
result += expression.charAt(i);
}
}
return result;
}
public static void processAnOperator(Stack<Integer> operandStack,Stack<Character> operatorStack) {
char op = operatorStack.pop();
int op1 = operandStack.pop();
int op2 = operandStack.pop();
//这里注意,别写成op1/op2。在expression中应该是op2/op1,因为op2先入栈
if(op == '+') {
operandStack.push(op2+op1);
}
else if(op == '-') {
operandStack.push(op2-op1);
}
else if(op == '*') {
operandStack.push(op2*op1);
}
else if(op == '/') {
operandStack.push(op2/op1);
}
}
}
最后
以上就是尊敬信封为你收集整理的Java实现简单的思维运算(只有加减乘除)的全部内容,希望文章能够帮你解决Java实现简单的思维运算(只有加减乘除)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复