后缀表达式求值

来源:互联网 发布:mac系统顿号怎么打 编辑:程序博客网 时间:2024/05/17 17:17

实现将一般的数学表达式转化为后缀表达式并求值

package expr;import java.util.Scanner;import linkStack.LinkStack;/** * 任务三:栈的应用--后缀表达式求值阅读教材及有关参考书。(1)利用任务一中实现的栈(SeqStack或者LinkStack),实现一位数字的整型后缀表达式求值程序,编写主函数测试算法正确性。(2)利用任务一中实现的栈(SeqStack或者LinkStack),实现实数(带小数点,位数不限)的后缀表达式求值程序,编写主函数测试算法正确性。 * @author asus * */public class ExprDemo2 {static LinkStack<Character> s=new LinkStack<Character>();static LinkStack<Double> s1=new LinkStack<Double>();public static void main(String args[]){Scanner sc=new Scanner(System.in);System.out.println("请输入要求值的表达式:");String str=sc.nextLine();System.out.println(str);s.add('#');String pstr=transformz(str);System.out.println(pstr);double result=Calcu(pstr);System.out.println(result);//12*(3+61)/8}public static String transformz(String str){String pstr="";for(int i=0;i<str.length();i++){char c=str.charAt(i);if((c>='0' && c<='9') || c=='.'){pstr=pstr+c;continue;}pstr=pstr+" "; if(c=='(')s.push(c);else if(c==')'){while(s.getTop()!='('){pstr+=s.pop();}s.pop();}else if(c=='+' || c=='-' || c=='*' || c=='/' || c=='%' || c=='^' ){char operator=s.getTop();while(Tokenpriority(c)<=Stackpriority(operator)){pstr=pstr+operator;s.pop();operator=s.getTop();}s.push(c);}}while(!s.isEmpty())pstr+=s.pop();return pstr.substring(0, pstr.length()-1);}private static int Tokenpriority(char operator) {if(operator=='+' || operator=='-')return 1;if(operator=='*' || operator=='/' || operator=='%')return 2;if(operator=='^')return 4;if(operator=='(')return 5;return -1;}private static int Stackpriority(char operator) {if(operator=='+' || operator=='-')return 1;if(operator=='*' || operator=='/' || operator=='%')return 2;if(operator=='^')return 3;if(operator=='(')return 0;return -1;}public static Double Calcu(String str){String pstr2="";for(int i=0;i<str.length();i++){char  c=str.charAt(i);if((c>='0' && c<='9') || c=='.'){pstr2=pstr2+c;continue;}if(pstr2.length()>0){Double n=Double.parseDouble(pstr2);s1.push(n.doubleValue());}if(c=='+' || c=='-' || c=='*' || c=='/' || c=='%' || c=='^' ){Double a=s1.pop();Double b=s1.pop();if(c=='+')s1.push(b+a);if(c=='-')s1.push(b-a);if(c=='*')s1.push(b*a);if(c=='/')s1.push(b/a);}pstr2="";}return s1.pop();}}//12.99289*(33.33+61)/8.3222


原创粉丝点击