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;
}
}
}
表达式计算
最新推荐文章于 2022-04-29 17:50:30 发布