Answer to Question #298986 in Java | JSP | JSF for Bruhh

Question #298986

2. Postfix Calculator

by CodeChum Admin

One good implementation of computing infix expressions is to transform them to postfix and then evaluate via the postfix expression.


Infix expressions is the common way of writing arithmetic expressions. The binary operator come between them as shown below:


More info here, Important!

https://pastebin.com/6qLXQ9Md

1
Expert's answer
2022-02-20T01:47:09-0500
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        for (int i = 0; i < n; i++) {
            String[] expression = in.nextLine().split(" ");
            Stack<Integer> stack = new Stack<>();
            for (String element : expression) {
                switch (element) {
                    case "+":
                        stack.push(stack.pop() + stack.pop());
                        break;
                    case "-":
                        stack.push(-stack.pop() + stack.pop());
                        break;
                    case "*":
                        stack.push(stack.pop() * stack.pop());
                        break;
                    case "/":
                        int b = stack.pop();
                        int a = stack.pop();
                        if (b != 0) {
                            stack.push(a / b);
                        } else {
                            System.out.println("Division by 0 Error");
                        }
                        break;
                    default:
                        stack.push(Integer.parseInt(element));

                }
            }
            if (stack.size() == 1) {
                System.out.println(stack.pop());
            }
        }

    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS