Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Stack;
- public class CSE220Assignment04 {
- public static void main(String[] args) {
- String exp=new Scanner(System.in).next();
- String postFixExp = postFixBuilder(exp);
- System.out.println("Post Fix Expression: "+postFixExp);
- int result = postFixEvaluator(add(postFixExp));
- System.out.println("Answer: "+result);
- }
- private static String add(String postFixExp) {
- String s ="";
- for (int i=0; i<postFixExp.length(); i++){
- s+=postFixExp.charAt(i)+" ";
- }
- return s;
- }
- public static String postFixBuilder(String exp){
- String result = "";
- Stack<Character> stack = new Stack<>();
- for (int i = 0; i<exp.length(); ++i)
- {
- char c = exp.charAt(i);
- if (Character.isLetterOrDigit(c))
- result += c;
- else if (c == '(')
- stack.push(c);
- else if (c == ')')
- {
- while (!stack.isEmpty() && stack.peek() != '(')
- result += stack.pop();
- if (!stack.isEmpty() && stack.peek() != '(')
- return "Invalid Expression";
- else
- stack.pop();
- }
- else // an operator is encountered
- {
- while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
- result += stack.pop();
- stack.push(c);
- }
- }
- while (!stack.isEmpty())
- result += stack.pop();
- return result;
- }
- static int Prec(char ch)
- {
- switch (ch)
- {
- case '+':
- case '-':
- return 1;
- case '*':
- case '/':
- return 2;
- case '^':
- return 3;
- }
- return -1;
- }
- public static int postFixEvaluator(String postfixExpr) {
- Stack<Integer> s = new Stack<Integer>();
- String[] items = postfixExpr.split(" ");
- for (String item : items) {
- try {
- s.push(Integer.valueOf(item));
- } catch (NumberFormatException e) {
- Integer value1 = s.pop();
- Integer value2 = s.pop();
- switch (item) {
- case "+":
- s.push(value2 + value1);
- break;
- case "-":
- s.push(value2 - value1);
- break;
- case "*":
- s.push(value2 * value1);
- break;
- case "/":
- s.push(value2 / value1);
- break;
- }
- }
- }
- return s.pop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement