package project_2;

public class PostfixEval {
	
	/*
	 * This Class Evaluate The postfix Expression
	 * */
	
	private static Stack<String> stack;

	public static String evaluate(String postfix){


		String []array = postfix.split(" ");
		stack = new Stack<>();

		String operand1;
		String operand2;
		String res;
		for(int i=0;i<array.length;++i){
			try{
				Integer.parseInt(array[i]);
				stack.push(array[i]);

			}
			catch (Exception e) {
				if(!(array[i].equals(""))){

					if(!isOperation(array[i])){
						return null;
					}
		
					else{
						operand1 =(String)stack.top();
						if(operand1!=null)
							stack.pop();
						else
							return null;

						operand2 =(String)stack.top();

						if(operand2!=null)
							stack.pop();
						else
							return null;

						res=evaluate(operand1, operand2, array[i]);
						if(res==null)
							return null;
						stack.push(res);
					}
				}
			}

		}
		String result = ((String)stack.top());
		stack.pop();
		if(!stack.isEmpty())
			return null;
		return result;
	}


	public static boolean isOperation(String s){
		String [] opp = {"*","/","+","-"};

		for (int i = 0; i < opp.length; i++) {
			if(s.equals(opp[i])){
				return true;
			}
		}
		return false;
	}
	
	

    //Evaluate an operation with two operand and return the result
	public static String evaluate(String operand1,String operand2,String operation){
		String res="";
		int result;
		if(operation.equals("*")){
			result = Integer.parseInt(operand2) * Integer.parseInt(operand1);

			res=String.valueOf(result);
			return res;
		}
		if(operation.equals("/")){
			if(Integer.parseInt(operand1)!=0){
				result = Integer.parseInt(operand2) / Integer.parseInt(operand1);

				res=String.valueOf(result);
				return res;
			}
			return null;
		}
		if(operation.equals("+")){
			if(Integer.parseInt(operand1)!=0){
				result = Integer.parseInt(operand2) +Integer.parseInt(operand1);

				res=String.valueOf(result);
			}
			return res;
		}
		if(operation.equals("-")){
			if(Integer.parseInt(operand1)!=0){
				result = Integer.parseInt(operand2) - Integer.parseInt(operand1);

				res=String.valueOf(result);
			}
			return res;
		}
		return res;
	}

}
