就不多说了,很简单,直接上代码。(注意在整个运算中没有涉及浮点数)
public class StackTest3 { private static Stacks1=new Stack (); //符号栈 private static Stack s2=new Stack (); //数字栈 public static void main(String[] args) { Scanner in=new Scanner(System.in); String s=in.next(); int by=0; for (int i = 0; i < s.length(); i++) { char ch=s.charAt(i); //当前字符 int flag = priority(ch); if(s2.isEmpty()==true&&(flag==1||flag==0)) { if(flag==1) { System.out.println("错误"); return; } s2.push(0); } if(flag==-1) { if(by>0) { Integer pop1 = s2.pop(); StringBuffer v1=new StringBuffer(String.valueOf(pop1)); v1.append(String.valueOf(ch)); int num = Integer.parseInt(v1.toString()); s2.push(num); by++; }else { s2.push(Integer.valueOf(String.valueOf(ch))); by++; } }else if(flag==1) { by=0; if(s1.isEmpty()==true||s1.peek()=='(') { s1.push(ch); }else { Character peek = s1.peek(); if(priority(peek)==1) { //当前的优先级小于或等于栈顶的优先级 Integer pop1 = s2.pop(); //数据栈中的第一个 元素 Integer pop2 = s2.pop(); //数据栈中的第二个元素 Character pop = s1.pop(); //字符栈中的栈顶元素 Integer num = yunsuan(pop2,pop1,pop); if(num==null) { System.out.println("错误"); return; } s1.push(ch); s2.push(num); }else if(priority(peek)==0) { s1.push(ch); } } }else if(flag==0) { //当前是 + 或- by=0; if(s1.isEmpty()==true||s1.peek()=='(') { s1.push(ch); }else { Character peek = s1.peek(); if(priority(peek)==1||priority(peek)==0) { //当前的优先级小于或等于栈顶的优先级 Integer pop1 = s2.pop(); //数据栈中的第一个 元素 Integer pop2 = s2.pop(); //数据栈中的第二个元素 Character pop = s1.pop(); //字符栈中的栈顶元素 Integer num = yunsuan(pop2,pop1,pop); if(num==null) { System.out.println("错误"); return; } s1.push(ch); s2.push(num); } } }else if(flag==2) { //左括号 by=0; s1.push(ch); }else if(flag==3) { //右括号 by=0; while(s1.peek()!='(') { Integer pop1 = s2.pop(); //数据栈中的第一个 元素 Integer pop2 = s2.pop(); //数据栈中的第二个元素 Character pop = s1.pop(); //字符栈中的栈顶元素 Integer num = yunsuan(pop2,pop1,pop); if(num==null) { System.out.println("错误"); return; } s2.push(num); } s1.pop(); } } while(s1.isEmpty()!=true) { Integer pop1 = s2.pop(); Integer pop2 = s2.pop(); Character pop = s1.pop(); Integer num = yunsuan(pop2,pop1,pop); if(num==null) { System.out.println("错误"); return; } s2.push(num); } System.out.println(s2.peek()); } public static int priority(char oper) { if(oper=='*'||oper=='/') { return 1; }else if(oper=='+'||oper=='-') { return 0; }else if(oper=='(') { return 2; }else if(oper==')') { return 3; }else { return -1; } } public static Integer yunsuan(Integer x,Integer y,Character pop) { if(pop=='+') { return x+y; }else if(pop=='-') { return x-y; }else if(pop=='*') { return x*y; }else if(pop=='/') { if(y==0) { return null; } return x/y; } return null; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)