-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.java
More file actions
46 lines (43 loc) · 1.51 KB
/
postfix.java
File metadata and controls
46 lines (43 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Stack;
import java.util.Scanner;
public class postfix{
public static int postfixEvaluate(String expression) {
Stack<Integer> stack = new Stack<>();
for (char c : expression.toCharArray()) {
if (Character.isDigit(c)) {
stack.push(c - '0');
} else {
int operand2 = stack.pop();
int operand1 = stack.pop();
int result = applyOperator(operand1, operand2, c);
stack.push(result);
}
}
return stack.pop();
}
public static int applyOperator(int operand1, int operand2, char operator) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
if (operand2 == 0) {
throw new ArithmeticException("Division by zero");
}
return operand1 / operand2;
default:
throw new IllegalArgumentException("Invalid operator");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the postfix expression:");
String postfixExpression = sc.nextLine();
int result = postfixEvaluate(postfixExpression);
System.out.println("Result of the postfix expression: " + result);
sc.close();
}
}