Untitled
unknown
plain_text
a year ago
2.4 kB
8
Indexable
import java.util.Scanner;
public class Main {
public static class Stack {
private int[] arr;
private int top;
private int capacity;
public Stack(int size) {
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x) {
if (top == capacity - 1) {
throw new RuntimeException("Stack Overflow");
}
arr[++top] = x;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack Underflow");
}
return arr[top--];
}
public boolean isEmpty() {
return top == -1;
}
}
public static int evaluatePostfix(String postfix) {
Stack stack = new Stack(postfix.length());
for (int i = 0; i < postfix.length(); i++) {
char c = postfix.charAt(i);
if (Character.isDigit(c)) {
stack.push(c - '0');
} else {
int operand2 = stack.pop();
int operand1 = stack.pop();
switch (c) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
stack.push(operand1 / operand2);
break;
case '^':
stack.push((int) Math.pow(operand1, operand2));
break;
default:
throw new IllegalArgumentException("Unsupported operator: " + c);
}
}
}
return stack.pop();
}
public static void main(String[] args) throws Exception {
System.setIn(new java.io.FileInputStream("Caculator3.txt"));
Scanner scanner = new Scanner(System.in);
System.out.print("Enter postfix expression (single-digit operands): ");
String postfix = scanner.nextLine();
int result = evaluatePostfix(postfix);
System.out.println("Evaluation result: " + result);
scanner.close();
}
}Editor is loading...
Leave a Comment