package tu;
import java.util.Stack;
public class EvaluateExpression {
public static void main(String[] args) {
//(1+2)*4-3
// ( 1 + 2 ) * 4 - 3
//根据空格拆分字符串数组
//主方法的参数个数
if(args.length != 1){
System.out.println("输入正确的表达式(前缀表达式、中缀表达式、后缀表达式)");
System.exit(1);
}
try{
System.out.println(evaluateExpression(args[0]));
}
catch(Exception e){
System.out.println("错误的表达式:"+args[0]);
e.printStackTrace();
}
// System.out.println("输出main参数个数:"+args.length);
// for(String str:args){
// System.out.println(str);
// }
}
private static int evaluateExpression(String ex) {
//中缀表达式求值,需要运算符栈,运算数栈
Stack <Integer> operandStack=new Stack<Integer>();
Stack <String> operatorStack=new Stack<String>();
ex=insertBlanks(ex);
//去掉首尾多余空格
ex=ex.trim();
//根据空格拆分字符串
String tokens[]=ex.split(" ");
if(tokens.length!=0){//表达式不空
for(String token:tokens){
//token是运算符+-*/、()、运算数
if(token.length()==0){//当前项不空
continue;
}
else if(token.charAt(0)=='+'||token.charAt(0)=='-'){
//1处理运算符栈顶操作
while(!operatorStack.isEmpty()&&(operatorStack.peek()=="+"||
operatorStack.peek()=="-"||
operatorStack.peek()=="*"||
operatorStack.peek()=="/")){
processAndOperator(operandStack,operatorStack);
}
//2运算符入栈
operatorStack.push(token);
}
else if(token.charAt(0)=='*'||token.charAt(0)=='/'){
while(!operatorStack.isEmpty()&&(
operatorStack.peek()=="*"||
operatorStack.peek()=="/")){
processAndOperator(operandStack,operatorStack);
}
operatorStack.push(token);
}
else if(token.trim().charAt(0)=='('){
operatorStack.push(token);
}
else if(token.trim().charAt(0)==')'){
while(operatorStack.peek() !="("){
processAndOperator(operandStack,operatorStack);
}
operatorStack.pop();
}
else{
//运算数直接入栈,注意将字符串运算数转换为整数
operandStack.push(new Integer(token));
}
}
//第二部分
//处理运算符栈的剩余操作
while(!operatorStack.isEmpty()){
processAndOperator(operandStack,operatorStack);
}
//第三部分
//运算数栈顶就是运算结果
return operandStack.pop();
}
else{
System.out.println("表达式不能为空");
return 0;
}
}
private static void processAndOperator(Stack<Integer> operandStack, Stack<String> operatorStack) {
//弹出运算符
String op=operatorStack.pop();
//弹出运算数,注意顺讯
int op2=operandStack.pop();
int op1=operandStack.pop();
//计算并将结果入栈
if(op=="+"){
operandStack.push(op1+op2);
}
else if(op=="-"){
operandStack.push(op1-op2);
}
else if(op=="*"){
operandStack.push(op1*op2);
}
else if(op=="/"){
operandStack.push(op1/op2);
}
}
public static String insertBlanks(String s){
String result="";
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||
s.charAt(i)==')'||
s.charAt(i)=='+'||
s.charAt(i)=='-'||
s.charAt(i)=='*'||
s.charAt(i)=='/'){//运算符左右加空格
result+=" "+s.charAt(i)+" ";
}
else{
result+=s.charAt(i);
}
}
return result;
}
}
https://blog.csdn.net/linweidong/article/details/5989889
return operandStack.pop();这一行有问题,这个栈里都没数据了你出栈就报错了,打个断点就知道了