前缀表达式转为后缀表达式;后缀表达式求值 java实现


package p;
import java.util.Scanner;
import java.util.Stack;

public class Main {
	public static String insertSpace(String s,int loc){
		s=s.substring(0,loc)+" "+s.substring(loc,s.length());
		return s;
		
	}
	
	public static int priority(char op){
		if(op=='+'||op=='-'){
			return 1;
		}
		else if(op=='*'||op=='/'){
			return 2;
		}
		return 0;
	}
	
	public static String findPost(String exp){
		Scanner in = new Scanner(exp);
		String pfexp="";
		Stack<Character> s =new Stack();
		while(in.hasNext()){
			if(in.hasNextDouble()){
				pfexp+=in.next();
			}
			else{
				char op=in.next().charAt(0);
				if(priority(op)>0){
					while(!s.isEmpty()&&priority(s.peek())>=priority(op)){
						pfexp+=s.pop();
						pfexp+=" ";
					}
					s.add(op);
				}
				else if(op=='('){
					s.add('(');
				}
				else if(op==')'){
					while(s.peek()!='('){
						pfexp+=s.pop();
						pfexp+=" ";
					}
					s.pop();
				}
				else{
					return "Error!";
				}
			}
			pfexp+=" ";
		}
		while(!s.isEmpty()){
			pfexp+=s.pop();
			pfexp+=" ";
		}
		return pfexp;
	}
	
	public static double pfCalculator(String exp){
		Scanner in = new Scanner(exp);
		String pfexp="";
		double a,b;
		Stack<Double> s =new Stack();
		while(in.hasNext()){
			if(in.hasNextDouble()){
				s.add(in.nextDouble());
			}
			else{
				a=s.pop();
				b=s.pop();
				char op=in.next().charAt(0);
				if(op=='+'){
					s.add(a+b);
				}
				else if(op=='-'){
					s.add(b-a);
				}
				else if(op=='*'){
					s.add(a*b);
				}
				if(op=='/'){
					s.add(b/a);
				}
			}
		}
		return s.pop();
	}
	public static void main(String[] args) {
		System.out.println("Input an expression:");
		Scanner input = new Scanner(System.in);
		String exp=input.next();
		
		for(int i=0;i<exp.length();i++){
			if(exp.charAt(i)=='+'||exp.charAt(i)=='-'||exp.charAt(i)=='*'||exp.charAt(i)=='/'||exp.charAt(i)=='('||exp.charAt(i)==')'){
				exp=insertSpace(exp,i);
				exp=insertSpace(exp,i+2);
				i++;
			}
		}
		System.out.println(exp);
		System.out.println(findPost(exp));
		System.out.println(pfCalculator(findPost(exp)));
	}
}



java没有getchar函数,所以将表达式分为多个字节。代码的缺点是无法进行负数的运算,括号匹配的检验也没有写。

你可能感兴趣的:(前缀表达式转为后缀表达式;后缀表达式求值 java实现)