Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package CS_240_Project_1;
- import java.util.*;
- public class RPN implements REPL {
- ArrayStack<Integer> stack;
- public RPN(){
- stack = new ArrayStack<Integer>();
- }
- public String[] read() {
- Scanner sc = new Scanner(System.in);
- System.out.print("rpn> ");
- String ans = sc.next();
- StringTokenizer s = new StringTokenizer(ans);
- int x = 0;
- String[] a = new String[30];
- while (s.hasMoreElements()) {
- a[x] = s.nextToken();
- x++;
- }
- return a;
- }
- public void eval(String expr) throws StackUnderflowException {
- if (isInt(expr)) {
- int x = Integer.parseInt(expr);
- stack.push(x);
- }
- else if (expr == "+") {
- int x = stack.pop();
- int y = stack.pop();
- stack.push(x+y);
- }
- else if (expr == "*") {
- int x = stack.pop();
- int y = stack.pop();
- stack.push(x*y);
- }
- else if (expr == "-") {
- int x = stack.pop();
- int y = stack.pop();
- stack.push(y-x);
- }
- else if (expr == "/") {
- int x = stack.pop();
- int y = stack.pop();
- stack.push(y/x);
- }
- else if (expr == "!") {
- while (!stack.isEmpty()) {
- stack.pop();
- }
- }
- else if (expr == ".") {
- System.out.println(stack.pop());
- }
- }
- public void eval(String[] exprs) throws StackUnderflowException {
- for (int i = 0; i <= exprs.length; i++) {
- eval(exprs[i]);
- }
- }
- public void print() throws StackUnderflowException {
- ArrayStack<Integer> stackCopy = stack;
- if (!stackCopy.isEmpty()) {
- System.out.println(stackCopy.pop());
- }
- }
- public void loop() throws StackUnderflowException {
- while (true) {
- read();
- print();
- }
- }
- public boolean isInt(String expr) {
- try { Integer.parseInt(expr);
- } catch (NumberFormatException E) {
- return false;
- }
- return true;
- }
- }
Add Comment
Please, Sign In to add comment