package project_2;

public class InfixToPos {

	/*
	 * This Class Convert from infix to postfix
	 */
	private static Stack<Character> stack;



	public static String EvaluateInfix(String infix){
		String postfix="";

		stack = new Stack<>();

		for (int i = 0; i < infix.length(); ++i) {
	
			 if(Character.isDigit(infix.charAt(i))){
				postfix+=infix.charAt(i);
				if(i+1<infix.length())
					if(!(Character.isDigit(infix.charAt(i+1)))){
						postfix+=" ";
					}
			}
			else{

				if(stack.isEmpty()){
					stack.push(infix.charAt(i));
				}
				
				else if(infix.charAt(i)==')' || infix.charAt(i)=='}' || infix.charAt(i)==']'){
		
					while(stack.top()!='(' && stack.top()!='{' && stack.top()!='['  ){
						postfix=postfix+stack.top();
						postfix+=" ";
						stack.pop();
					}
					stack.pop();
				}
				else if(infix.charAt(i)=='('  || infix.charAt(i)=='{' || infix.charAt(i)=='['){
					stack.push(infix.charAt(i));

				}
				else if(highPrec(infix.charAt(i), (Character)stack.top())){

					stack.push(infix.charAt(i));
				}

				else{
					while( !(stack.isEmpty())&& !(highPrec(infix.charAt(i), (Character)stack.top())) ){
						postfix=postfix+stack.top();
						postfix+=" ";
						stack.pop();	
					}
					stack.push(infix.charAt(i));
				}

			}
		}


		while(!(stack.isEmpty())){
			postfix+=" ";
			postfix+=stack.top();

			stack.pop();
		}
		return postfix;


	}
	
	//Determine if a operation is high from other operation
	public static boolean  highPrec(Character a,Character b){
		if(a.equals('*') || a.equals('/') ){
			if(b.equals('*') || b.equals('/'))
				return false;
			else
				return true;
		}

		if(a.equals('+') || a.equals('-')){
			if(b.equals('+') || b.equals('-')|| b.equals('*') || b.equals('/'))
				return false;
			else
				return true;
		}
		return true;
	}




}
