表达式求值

//code :[email protected]:PHIILL_01/demo.git

package com.synnex.calc;

import java.util.List;

public class Calcer {

    private TokenStack optStack = new TokenStack();

    private TokenStack numberStack = new TokenStack();

    public static void main(String[] args) {
	Calcer calc = new Calcer();
	System.out.println("RS=>" + calc.calc("(3+2)*(7/9)"));
    }

    public int calc(String expr) {
	TokenParser parser = new TokenParser(expr);
	List<IToken> tokens = parser.parse();
	int size = tokens.size();
	for(int i = 0 ; i < size ;i ++){
	    IToken cuurentToken = tokens.get(i);
	    if(IToken.type_number.equals(cuurentToken.getType())){
		numberStack.peer(cuurentToken);
		if(optStack.isEmpty()){
		    continue;
		}
		IToken nextOptToken = getNextOptToken(tokens, i);		
		if(null == nextOptToken){
		    while(!optStack.isEmpty()){	
			doStackData(optStack.pop());
		    }
		}else {
		    IToken lastToken = optStack.getFirstToken();
		    if(lastToken.getPriority()>= nextOptToken.getPriority()){
			doStackData(optStack.pop());
		    }
		}
		
	
	    }
	    if(IToken.type_opt.equals(cuurentToken.getType())){
		optStack.peer(cuurentToken);
	    }
	    
	}
	// Fixed最后一个字符不为操作数
	while(!optStack.isEmpty()){	
		doStackData(optStack.pop());
	}
	
	return TokenDefine.getNumber(numberStack.pop());
    }

    private  IToken  getNextOptToken(List<IToken> tokens , int cuurentIndex){
	for(int i =cuurentIndex ; i<tokens.size() ;i++ ){
	    IToken iToken = tokens.get(i);
	    if(IToken.type_opt.equals(iToken.getType())){
		return iToken;
	    }
	}
	return null;
    }
    
    
    private void doStackData(IToken optToken) {	
	if(optToken.getValue().equals("(") || 
		optToken.getValue().equals(")")
		){
	    return;
	}
	if(numberStack.getSize()<2){
	    return ;
	}
	IToken last = numberStack.pop();
	IToken lastPre = numberStack.pop();
	int optNum1 = TokenDefine.getNumber(lastPre);
	int optNum2 = TokenDefine.getNumber(last);
	int rs = 0;
	if (optToken.getValue().equals("+")) {
	    System.out.println(optNum1 + "+" + optNum2);
	    rs = optNum1 + optNum2;
	} else if (optToken.getValue().equals("-")) {
	    rs = optNum1 - optNum2;
	    System.out.println(optNum1 + "-" + optNum2);
	} else if (optToken.getValue().equals("*")) {
	    rs = optNum1 * optNum2;
	    System.out.println(optNum1 + "*" + optNum2);
	} else if (optToken.getValue().equals("/")) {
	    rs = optNum1 / optNum2;
	    System.out.println(optNum1 + "/" + optNum2);
	}
	numberStack.peer(new Token(IToken.type_number, 0, String.valueOf(rs)));

    }

}

点赞