Question

In: Computer Science

Write a Reverse Polish Calculator, RPN We discussed in class a general implementation of RPN using...

Write a Reverse Polish Calculator, RPN

We discussed in class a general implementation of RPN using a stack to keep track of the numbers. Each time an operand is encountered, two values are popped from this stack, the given operation is performed, and the result is pushed back onto the stack. Utilize Java generic Stack Class to implement this algorithm with four arithmetic operations: +, *, -, /.

It is suggested that you implement a class RPN with a single static method evaluate. This method should have the following signature:

public static String evaluate(String expression)

It should split the passed expression into (a string array of) tokens by invoking splitmethod of String class. This array can then be processed one element at a time (perhaps another method): each time a number is found – it is pushed on a stack. Each time an operation is found – two numbers are popped from the stack, the given operation is performed, and the result is pushed back on the stack. If the passed expression was a properly formed RPN, the last element on the stack represents the result. It should be returned as a string. If the given expression is not valid, evaluate should return a string denoting a syntax error.Your main should continually ask the user to input a potential RPN string which would be passed to the evaluate method. In order to terminate the procedure, the user would input an empty string (carriage return)

Solutions

Expert Solution

// RPN.java

import java.util.Scanner;
import java.util.Stack;

public class RPN {

   // method to evaluate an input string representing a postfix expression consisting only of numbers
   // and operators (+, - , * and /) and returns the result of the expression, if valid
   // else returns "syntax error" if invalid
   public static String evaluate(String expression)
   {
       // split the input expression into array of strings using space as the delimiter
       String[] tokens = expression.split(" ");
       // create an empty stack of double
       Stack<Double> stack = new Stack<Double>();
      
       // loop over the tokens
       for(int i=0;i<tokens.length;i++)
       {
           // operator
           if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/"))
           {
               // invalid expression
               if(stack.isEmpty())
                   return "syntax error";
               double op2 = stack.pop(); // get the top number of stack
               if(stack.isEmpty()) // invalid expression
                   return "syntax error";
               double op1 = stack.pop(); // get the second top number of stack
              
               // based on operator perform the operation and push the result back to stack
               if(tokens[i].equals("+"))
                   stack.push(op1 + op2);
               else if(tokens[i].equals("-"))
                   stack.push(op1 - op2);
               else if(tokens[i].equals("*"))
                   stack.push(op1 * op2);
               else
               {
                   if(op2 == 0) // divide by zero error
                       return "syntax error";
                   else
                       stack.push(op1 / op2);
               }
           }else // number i.e operand, insert it on top of stack
           {
               stack.push(Double.parseDouble(tokens[i]));
           }
       }
      
       // after evaluation get the top element of stack
       String result = stack.pop() + "";
       if(!stack.isEmpty()) // stack is not empty, syntax error
           result = "syntax error";
       return result;
   }
  
   public static void main(String[] args) {

       String expression;
       Scanner scan = new Scanner(System.in);
       // loop that continues until the user exits
       do
       {
           // input the expression
           System.out.println("Enter RPN string(operands and operators separated by spaces), blank to exit: ");
           expression = scan.nextLine();
           // check if user wants to exit
           if(expression.length() > 0)
               System.out.println(evaluate(expression)); // evaluate and display the result
       }while(expression.length() > 0);
   }

}

//end of RPN.java

Output:


Related Solutions

REVERSE POLISH CALCULATOR C++ ONLY. For this assignment, you are to write a program, which will...
REVERSE POLISH CALCULATOR C++ ONLY. For this assignment, you are to write a program, which will calculate the results of Reverse Polish expressions that are provided by the user. You must use a linked list to maintain the stack for this program (NO array implementations of the stack). You must handle the following situations (errors): Too many operators (+ - / *) Too many operands (doubles) Division by zero The program will take in a Polish expression that separates the...
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator! Create a base class called...
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator! Create a base class called Operand Give it a virtual destructor to avoid any weird problems later on! Derive a class called Number from Operand Maintain a double member variable in class Number For simplicity, you may make the member variable public if you would like Derive a class called Operator from Operand Derive a class called Add from Operator (2 + 3 = 5) Derive a class called...
Reverse Polish (HP) Style Calculator - Part 2 The purpose of this assignment is to incorporate...
Reverse Polish (HP) Style Calculator - Part 2 The purpose of this assignment is to incorporate an abstract class and inheritance and add it to the interface of the business calculator created in Topic 4. • Implement a pure abstract stack class named AbstractStack that has no implementation. It will not have a private array of double, because that is an implementation detail of ArrayStack that would not be found in other implementations such as LinkedStack. Nor will it have...
Task 1: [10 Marks] Write a function “reverse” in your queue class (linked list implementation) that...
Task 1: [10 Marks] Write a function “reverse” in your queue class (linked list implementation) that reverses the whole queue. In your driver file (main.cpp), create an integer queue, push some values in it, call the reverse function to reverse the queue and then print the queue.
Write in Java! (Not Javascript) Consider the LinkedList class we discussed in class (see the slides...
Write in Java! (Not Javascript) Consider the LinkedList class we discussed in class (see the slides for lecture 8). Add the following methods to the class and submit the completed LinkedList class. int size() which returns the size of the linked list Link getElementByIndex(int index) which returns the Link/node specified by the index. For example, getElementByIndex(0) should return the first Link, getElementByIndex(2) should return the third Link. If index is not in range, your method should return null. boolean hasDuplicate()...
B. Compare and contrast these two case studies: The first one we discussed in class, General...
B. Compare and contrast these two case studies: The first one we discussed in class, General Motors (GM), which decided to offshore production from the USA to Mexico. When GM began this in the late 70s, it was a relatively new idea for a major American producer, and was highly controversial, but the trend has grown over the decades, and nowadays other major car companies, including European and Asian giants like BMW and Honda, have followed the same strategy to...
As we discussed in class, the US Treasury bond rate is determined using an auction process....
As we discussed in class, the US Treasury bond rate is determined using an auction process. Thoroughly discuss how the bond auction process operates
Write an implementation of the set class, with associated iterators using a binary search tree. Add...
Write an implementation of the set class, with associated iterators using a binary search tree. Add to each node a link to the parent node. (C++)
In class, we discussed the security market line (SML). Explain this concept to your friend using...
In class, we discussed the security market line (SML). Explain this concept to your friend using an appropriate diagram? If a security's expected return versus risk is plotted above or below the SML what does this imply?
How to write a max-heap implementation of a templated priority queue class using the STL std::vector...
How to write a max-heap implementation of a templated priority queue class using the STL std::vector class to hold the data array
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT