java中缀表达式转为后缀表达式出错

林之木 发布于 2013/01/03 18:13
阅读 391
收藏 0

    本人刚开始学java不久,由于想做个四则混合运算的计算器。代码中用到中缀表达式转后缀表达式的算法,网上搜索了一些代码进行了一些更改,但是运行时结果就是总出错!具体出错的地方是:在运行代码时,主函数中的中缀表达式第二个除号的地方好像没有进行比较而是直接入栈了,照成输出结果出错!

研究了一天没找到错误的原因~~~所以,希望高手能够指点一下!在下感激不尽~~~~

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class ExpressionTrans{
	private Stack<Double> numStack = new Stack<Double>();//操作数栈
	private Stack<String> optStack = new Stack<String>();//操作符栈
	private String expression;//算式表达式
	private double result = 0;//结果
	//设置优先级表
	private Map<String,Integer> priorMap = new HashMap<String,Integer>();
	//具体的操作符优先级
	public ExpressionTrans(){
		priorMap.put("+", 1);
		priorMap.put("-", 1);
		priorMap.put("*", 2);
		priorMap.put("/", 2);
	}
	//获取操作符优先级
	public int getPrior(String opt){
		return priorMap.get(opt);
	}
	//判断操作符优先级是否为最高
	public boolean isHighprior(String opt){
		int optPrior = getPrior(opt);
		if(!optStack.empty()){
			for(String s:optStack){
				int prior = getPrior(s);
				if(optPrior > prior)
					return true;
			}
		}
		return false;
	}
	//求后缀表达式
	public String expTrans(){
		int index = 0;
		int end = 0;
		String Ipn = "";
		for(int i = 0;i<expression.length();i++){
			String temp = String.valueOf(expression.charAt(i));
			if(temp.matches("[0-9.]")){
				end++;
			}
			else{
				String tempnum = expression.substring(index, end);
				Ipn += tempnum + ",";
				String tempopt = expression.substring(end,++end);
				if(tempopt.equals("=")){			//如果输入字符串结束
					while(!optStack.empty()){
						Ipn += optStack.pop() + ",";
						//Ipn = Ipn.substring(0, Ipn.length()-1);
					}
				}
				else{								//字符串未结束
					/*if(optStack.empty()){
						optStack.push(tempopt);
					}
					else */
					
					if(isHighprior(tempopt)){		//压栈
						optStack.push(tempopt);
					}
					else{
						while(!optStack.empty()){
							String topOptStack = optStack.peek();
							if(getPrior(topOptStack) >= getPrior(tempopt)){
								Ipn += optStack.pop() + ",";
							}
							else
								//optStack.push(topOptStack);
								continue;
						}
						optStack.push(tempopt);
					}
				}
				//end++;
				index = end;
			}
		}
		return Ipn;
	}
	//计算后缀表达式
	public double calculate(String[] Ipn){
		for(int i = 0;i<Ipn.length;i++){
			if(Ipn[i].matches("^[0-9]+.?[0-9]*$")){
				numStack.push(Double.parseDouble(Ipn[i]));
			}
			else{
				calnum(Ipn[i]);
			}
		}
		return result;
	}
	//计算
	public void calnum(String operator){
		double num1 = numStack.pop();
		double num2 = numStack.pop();
		if(operator.equals("+")){
			result = num2 + num1;
		}
		if(operator.equals("-")){
			result = num2 - num1;
		}
		if(operator.equals("*")){
			result = num2 * num1;
		}
		else if(operator.equals("/")){
			result = num2 / num1;
		}
		numStack.push(result);
	}
	
	public void setExpression(String expression){
		this.expression = expression;
	}
	
	public static void main(String[] args){
		ExpressionTrans cal = new ExpressionTrans();
		String expression = "1+2+2*3+4/2/2+5=";
		cal.setExpression(expression);
		String[] Ipn=cal.expTrans().split(",");
		for(int i=0;i<Ipn.length;i++)   
	        System.out.print(Ipn[i]);
		System.out.println("");
		System.out.println(cal.calculate(Ipn));
	}
}

 

加载中
0
xwz
xwz
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class T {
	public static void main(String[] args) {
		System.out.println(calc("1+1*(9-7)")); // 结果 3.0
	}

	private static Object calc(String str) {
		try {
			ScriptEngineManager MANAGER = new ScriptEngineManager();
			ScriptEngine engine = MANAGER.getEngineByName("javascript");
			return engine.eval(str);
		} catch (ScriptException e) {
		}
		return null;
	}
}
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部