字符串表達式(先轉後綴)

package 字符串表達式先變中綴;

import java.util.Stack;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	//	String[] strs={"3","*","(","(","2","+","1",")","*","6","-","1",")","-","8","/","2","+","1"};
		String[] strs={"3","*","(","(","2","+","1",")","*","6","-","1",")","-","(","8","/","2","+","1",")","+","2"};
		Stack<Object> stack=new Stack<>();
		Stack<String> stack2=new Stack<>();
		for(int i=0;i<strs.length;++i){
			String nowStr=strs[i];
			if(nowStr.charAt(0)>='0'&&nowStr.charAt(0)<='9'){
				stack.push(Double.parseDouble(nowStr));
				if(stack2.size()>0&&(stack2.peek().equals("*")||stack2.peek().equals("/"))){
					String work= stack2.pop();
					stack.push(work);
				}
			}
			else{
				if(nowStr.equals("(")){
					stack2.push(nowStr);
				}
				else if(nowStr.equals(")")){
					String work= stack2.peek();
					if(!work.equals("(")){
						stack2.pop();
						stack.push(work);
						stack2.pop();
						if(stack2.size()>0&&(stack2.peek().equals("*")||stack2.peek().equals("/"))){
							stack.push(stack2.pop());
						}
					}else{
						stack2.pop();
					}
				}
				else if(nowStr.equals("+")||nowStr.equals("-")){
					if(stack2.size()>0){
						String lastWork=stack2.peek();
						if(lastWork.equals("+")||lastWork.equals("-")){
							stack.push(lastWork);
							stack2.pop();
							stack2.push(nowStr);
						}else{
							stack2.push(nowStr);
						}
					}else{
						stack2.push(nowStr);
					}
				}else if(nowStr.equals("*")||nowStr.equals("/")){
					stack2.push(nowStr);
				}
			}
		}
		if(!stack2.isEmpty()){
			stack.push(stack2.pop());
		}
		for(int i=0;i<stack.size();++i){
			System.out.print(stack.get(i).toString()+" ");
		}
		
		Stack<Double> resultStack=new Stack<>();
		for(int i=0;i<stack.size();++i){
			Object obj=stack.get(i);
			if(obj instanceof Double){
				resultStack.push((Double) obj);
			}else{
				String work=(String) obj;
				
				Double a2=resultStack.pop();
				Double a1=resultStack.pop();
					
				if(work.equals("+")){
					resultStack.push(a1+a2);
				}
				else if(work.equals("-")){
					resultStack.push(a1-a2);
				}else if(work.equals("*")){
					resultStack.push(a1*a2);
				}else if(work.equals("/")){
					resultStack.push(a1/a2);
				}
			}
		}
		System.out.println();
		System.out.println(resultStack.peek().toString());
	}
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章