后缀表达式求值

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

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值