表达式计算
2018-03-30 21:54
162 查看
import java.util.Scanner; import java.util.Stack; import java.util.LinkedList; public class Main{ public static void main(String[] args) { Scanner scanner=new Scanner(System.in); while(scanner.hasNext()) { String string=scanner.nextLine(); //将中缀表达式转化为后缀表达式 LinkedList<Object> link=new LinkedList<Object>();//后缀表达式 Stack<Character> opstack=new Stack<Character>();//操作符栈 int x=0; boolean isInt=false; for(int i=0;i<string.length();i++) { char ch=string.charAt(i); if(ch>='0' && ch<='9') { x=x*10+ch-'0'; isInt=true; } else { if(isInt) link.add((Integer)x); x=0; isInt=false; if(ch=='(') { opstack.push(ch); } else if(ch==')') { while(opstack.peek()!='(') { link.add(opstack.pop()); } opstack.pop(); } else { while(!opstack.empty() && priority(opstack.peek())>=priority(ch)) link.add(opstack.pop()); opstack.push(ch); } } } if(x!=0) link.add(x); while(!opstack.empty()) link.add(opstack.pop()); //计算后缀表达式的值 Stack<Integer> integers=new Stack<Integer>(); for(Object every:link) { if(every instanceof Integer) { integers.push((Integer)every); } else { int b=integers.pop(); int a=integers.pop(); char op=(Character)every; if(op=='+') integers.push(a+b); else if(op=='-') integers.push(a-b); else if(op=='*') integers.push(a*b); else integers.push(a/b); } } System.out.println(integers.peek()); } scanner.close(); } //求运算符的优先级,不考虑数字和() public static int priority(char op) { switch(op) { case '*': case '/':return 2; case '+': case '-':return 1; default:return 0; } } }
相关文章推荐
- .NET平台开源项目速览(8)Expression Evaluator表达式计算组件使用
- HDU--2206 -- IP的计算 [正则表达式]
- 栈计算表达式
- java表达式计算
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- 九度+计算表达式模拟+scanf读取数据的灵活运用和运算级的处理
- C语言实验——计算表达式
- 栈的应用--计算字符串表达式
- 计算表达式的值c++逆波兰式实现方法
- 也谈表达式分析和计算
- 项目问题1:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
- Oracle计算时间差表达式
- 图解后缀表达式的计算过程
- C语言实验——计算表达式
- c语言作业,,输入表达式并计算表达式的值
- 关于表达式计算的问题
- 字符串表达式计算 (使用DATATABLE)
- 正则表达式关于次数的计算
- 栈应用(中缀表达式转后缀表达式并计算后缀表达式的值)
- BB Gap Report的计算方法以及有用的MDX查询表达式(对于Property,Aspect等不同Dimension的过滤)