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
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());
}
}
}
}
Comments
Leave a comment