import java.util.Scanner; public class jklj { //假定无括号 public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String str=sc.nextLine(); Stack ds ;//数据栈 FStack fs;//符号栈 while(n--!=0) { str = sc.nextLine(); ds = new Stack(); fs = new FStack(); char[] ch = str.toCharArray(); int l = 0 ; /* * 如果是符号 把其之前的数字提取 * 存入数据栈中 * 然后判断当前符号和符号栈中的符号优先级,再决定是否取出数据进行运算 */ for(int i = 0 ; i<ch.length;i++) { if(Type(ch[i]))//如果是符号 { int count = 1; int f =0; int t = i-1; while(t>=l) { f+= (ch[t]-'0')*count; count *= 10; t--; } l=i+1; ds.push(f);//数据入栈 //判断是否要进行运算 //考虑 数据栈的数是够用的 while(!fs.isEmpty()&&Judge(fs.peek(),ch[i]) ) { int b = ds.pop(); int a = ds.pop(); char ppp = fs.pop(); switch(ppp) { case '+':ds.push(a+b);break; case '-':ds.push(a-b);break; case '*':ds.push(a*b);break; case '/':ds.push(a/b);break; } } fs.push(ch[i]); } } int count = 1; int f =0; int t = ch.length-1; while(t>=l) { f+= (ch[t]-'0')*count; count *= 10; t--; } ds.push(f);//数据入栈 while(!fs.isEmpty()) { int b = ds.pop(); int a = ds.pop(); char ppp = fs.pop(); switch(ppp) { case '+':ds.push(a+b);break; case '-':ds.push(a-b);break; case '*':ds.push(a*b);break; case '/':ds.push(a/b);break; } } System.out.println(ds.peek()); } } //判断是否要进行运算 private static boolean Judge(char peek, char c) { int a = F(peek); int b = F(c); if(b<=a) return true; return false; } private static int F(char peek) { if(peek == '*'||peek =='/') return 1; return 0; } private static boolean Type(char c) { if(c =='+'||c =='-'||c =='*'||c =='/') return true; return false; } }
//数据栈 class Stack { int top ; int data[]; public Stack() { data = new int [100]; top = -1; } public void push(int item) { data[++top] = item; } public int pop() { return data[top--]; } public boolean isEmpty() { if(top == -1) return true; return false; } public int peek() { return data[top]; } }
//符号栈 class FStack { int top ; char data[]; public FStack() { data = new char [100]; top = -1; } public void push(char item) { data[++top] = item; } public char pop() { return data[top--]; } public boolean isEmpty() { if(top == -1) return true; return false; } public char peek() { return data[top]; } }
表达式求值
最新推荐文章于 2021-09-23 18:07:17 发布