Java实现中序表达式的实例代码
什么是中序表达式
前序(前缀)表达式要求每一个操作符出现在其操作数之前.一般不用. 写表达式的后序表达式一般是为了便利于计算机编程中栈的实现,所以用的较多.
具体代码如下所示:
package 表达式求值; import java.util.Stack; /* * 中序表达式求值实现 */ public class CenterExpression { public double evaluate(String expression){ //传入中序表达式 char [] ex = expression.toCharArray(); Stack<Double> num = new Stack<>(); Stack<Character> ops = new Stack<>(); for(int i = 0; i < ex.length; i++){ //循环将表达式依次入栈 char c = ex[i]; if(c < '9' && c > '0'){ num.push(Double.parseDouble(Character.toString(c))); } else if(c == '('){ ops.push('('); } else if(c == ')'){ while(true){ char op = ops.pop(); if(op == '('){ break; } else{ switch(op){ case '+':num.push(num.pop()+num.pop());break; case '-':num.push(num.pop()-num.pop());break; case '*':num.push(num.pop()*num.pop());break; case '/':num.push(num.pop()/num.pop());break; default:break; } } } } else if(ops.empty() && (c == '+' || c == '-' || c == '*' || c == '/')){ ops.push(c); } else if(!ops.isEmpty() && (c == '+' || c == '-' || c == '*' || c == '/')){ char op =ops.peek(); while((op == '*' || op == '/') && (c == '+' || c == '-')){ op = ops.pop(); switch(op){ case '+':num.push(num.pop()+num.pop());break; case '-':num.push(num.pop()-num.pop());break; case '*':num.push(num.pop()*num.pop());break; case '/':num.push(num.pop()/num.pop());break; default:break; } if(ops.isEmpty()){ break; } else{ op = ops.peek(); } } ops.push(c); } } while(!ops.isEmpty()){ //处理剩余可以按计算机扫描顺序处理的表达式 char op =ops.pop(); switch(op){ case '+':num.push(num.pop()+num.pop());break; case '-':num.push(num.pop()-num.pop());break; case '*':num.push(num.pop()*num.pop());break; case '/':num.push(num.pop()/num.pop());break; default:break; } } return num.pop(); } public static void main(String [] args){ CenterExpression exp = new CenterExpression(); System.out.println(exp.evaluate("1*2+5*3")); } }
总结
以上所述是小编给大家介绍的Java实现中序表达式的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
赞 (0)