表式は値を求めます(中缀式は后丁式を回転して、后丁式は値を求めます)NYOJ 53はテストして通します


テストアドレス:http://acm.nyist.net/JudgeOnline/problem.php?pid=35
package calc;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Main {
	//    
	static LinkedList<String> opStack=new LinkedList<String>();
	//     
	static Map<String, Integer> priority=new HashMap<String, Integer>(){
		{
			put("(", 0);
			put(")", 0);
			put("+", 1);
			put("-", 1);
			put("*", 2);
			put("/",2);
		}
	};
	/**
	 *      :
	 * 		         
	 * 		a:        
	 * 		b:  (    
	 * 		c:  )            ,    (  , (    
	 * 		d  :                      ,          ,          ;        
	 */
	public static List<String> midToAfter(String [] mid){
		LinkedList<String> after=new LinkedList<String>();
		int index=0;
		for(String ss:mid){
			if(ss.equals("=")) continue;
			if(priority.get(ss)==null){//      
				after.add(ss);
			}else if(ss.equals("(")){
				opStack.push(ss);
			}else if(ss.equals(")")){
				while(!opStack.peek().equals("(")){//  “(”,   ,
					after.add(opStack.pop());
				}
				opStack.pop();//  (
			}else {
				while(!opStack.isEmpty()&&priority.get(ss)<=priority.get(opStack.peek())){
					after.add(opStack.pop());
				}
				opStack.push(ss);
			}
		}
		while(!opStack.isEmpty()) after.add(opStack.pop());
		return after;
	}
	/**
	 *     :           
	 * 		a:    ,    
	 * 		b:     ,         ,      ,      ,           
	 * 		  :          ,      
	 * @param after
	 * @return
	 */
	public static double afterValue(List<String> after){
		LinkedList<Double> number=new LinkedList<Double>();
		for(String ss:after){
			if(priority.get(ss)!=null){//    ,     ,           
				Double y=number.pop();
				Double x=number.pop();
				if(ss.equals("+")) number.push(x+y);
				else if(ss.equals("-")) number.push(x-y);
				else if(ss.equals("*")) number.push(x*y);
				else if(ss.equals("/")) number.push(x/y);
			}else{
				number.push(Double.valueOf(ss));
			}
		}
		return number.pop();
	}
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		String s;
		in.nextLine();//             
		while(n--!=0){
			//s=in.nextLine();
			s=in.nextLine();
			//     
			int pre=-1;//        ,        :)*      :*#     :#*#
			StringBuffer sb=new StringBuffer();
			for(int i=0;i<s.length();i++){
				if(s.charAt(i)!='.'&&(s.charAt(i)<'0'||s.charAt(i)>'9')){
					if(i-1==pre){ //         
						sb.append(s.charAt(i)+"#");	
					}
					else sb.append("#"+s.charAt(i)+"#");
					pre=i;//  pre
				}else{
					sb.append(s.charAt(i));
				}
			}
			String[] split = sb.toString().split("#");
			List after=midToAfter(split);
			double ans=afterValue(after);
			System.out.printf("%.2f
",ans); } } }