天天看點

中綴表達式轉字尾表達式并計算(十位以内)

import java.util.Scanner;

public class Main {

	public static void main(String args[]){
		Scanner in = new Scanner(System.in);
		
		String str = in.nextLine();
		in.close();
		int len = str.length();
		int i=0,chtop=0,optop=0;
		char ch;
		char chs[] = new char[100];
		char ops[] = new char[100];
		chs[chtop] = '#';
		ops[optop] = '#';
		
		for(i=0;i<len;i++){
			ch = str.charAt(i);
			if(isOperator(ch)){
				if(advance(ch) > advance(ops[optop])){
					ops[++optop]=ch;
				}else{
					while(advance(ch)<=advance(ops[optop])){
						chs[++chtop] = ops[optop--];
					}
					ops[++optop]=ch;
				}
			}else if(ch == '('){
				ops[++optop]=ch;
			}else if(ch == ')'){
				while(ops[optop]!='('){
					chs[++chtop]=ops[optop--];
				}
				
				optop--;
						
			}else{
				chs[++chtop]=ch;
				
			}
		}
		while(ops[optop]!='#')
		{
			chs[++chtop]=ops[optop--];
		}
	
		int nums[] = new int[100];
		int numtop = -1,result = 0;
		for(i=1;i<=chtop;i++){
			if(isOperator(chs[i])){
				int b = nums[numtop--];
				int a = nums[numtop--];
				switch (chs[i]) {
				case '+':
					result = a+b;
					break;
				case '-':
					result = a-b;
					break;
				case '*':
					result = a*b;
					break;
				case '/':
					result = a/b;
				default:
					break;
				}
				nums[++numtop]=result;

			}else{
				nums[++numtop]=chs[i]-'0';
			}
		}
		
		System.out.print(result);
		
	}
	
	private static boolean isOperator(char ch) {
		if(ch == '+' || ch == '-' || ch == '*' || ch =='/'){
			return true;
		}else {
			return false;
		}
	}
	private static int advance(char ch) {
		
		if(ch=='+' || ch=='-') return 1;
		else if(ch=='*' || ch=='/') return 2;
		else if(ch == ')') return 3;
		else return 0;		
		
	}
}
           

繼續閱讀