Question

In: Computer Science

Write a Reverse Polish Calculator, RPN in JAVA Each time an operand is encountered, two values...

Write a Reverse Polish Calculator, RPN in JAVA

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: +, *, -, /.

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 split method 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).

Sample run of how it should look:

run:

Enter an RPN expression or to exit

2 3 4 +

7.0

extra junk ignored

Enter an RPN expression or to exit

2 3 4 + *

14.0

Enter an RPN expression or to exit

2 3 + +

Syntax error

Enter an RPN expression or to exit

10 6 1 - /

2.0

Enter an RPN expression or to exit

5 4 3 / /

3.75

Enter an RPN expression or to exit

  

good bye

Solutions

Expert Solution

Here is code in Java:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class Solution{

    // Method to evaluate value of a postfix expression
    public static double evalRPN(String[] tokens) {
        double a,b;
        Stack<Double> S = new Stack<Double>();
        for (String s : tokens) {

            if(s.equals("+")) {
                b= S.pop();
                if(S.empty()){
                    System.out.println("Invalid input");
                    break;
                }
                a= S.pop();
                S.add(a+b);
            }
            else if(s.equals("/")) {
                b = S.pop();
                if(S.empty()){
                    System.out.println("Invalid input");
                    break;
                }
                a = S.pop();
                S.add(a / b);
            }
            else if(s.equals("*")) {
                b= S.pop();
                if(S.empty()){
                    System.out.println("Invalid input");
                    break;
                }
                a= S.pop();
                S.add(a* b);
            }
            else if(s.equals("-")) {
                b = S.pop();
                if(S.empty()){
                    System.out.println("Invalid input");
                    break;
                }
                a = S.pop();
                S.add(a - b);
            }
            else {
                S.add(Double.parseDouble(s));
            }
        }
        return S.pop();
    }

    // Driver program to test above functions
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        while(true){
            System.out.println("Enter an RPN expression or <CR> to exit\n");
            String inp = sc.nextLine();
            if(inp.equals("end"))
                break;
            List<String> L = new ArrayList<String>();
            // to split the given input
            for (String val: inp.split(" ")){
                L.add(val);

            }
            String tokens[] = new String[L.size()];
            tokens = L.toArray(tokens);
            try {
                double output = evalRPN(tokens);
                System.out.println(output);
            }catch (Exception e){
                System.out.println("Invalid input");
            }
        }
    }
}

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...
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...
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...
This code needs to run a working Reverse Polish Calculator, but when I input my commands...
This code needs to run a working Reverse Polish Calculator, but when I input my commands it only pops my inputs never push them. So my answer is always zero. Here is my code. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> struct Node { int element; struct Node *next; }; //Global variable struct Node *top = NULL; void push(int ele) { struct Node *newNode; newNode = (struct Node *) malloc(sizeof(struct Node)); newNode->element = ele; newNode->next = top; top = newNode; }...
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...
Time Calculator – Intro To Programming - JAVA Write a program that asks the user to...
Time Calculator – Intro To Programming - JAVA Write a program that asks the user to enter a number of seconds. • There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds. • There are 3,600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to...
Java program Reverse polish notation: using stack - You can use the Stack included in java.util.Stack...
Java program Reverse polish notation: using stack - You can use the Stack included in java.util.Stack (or your own implementation) for this problem. Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free. Write a program which...
(In Java) Write three static functions that each take two double values which represent the two...
(In Java) Write three static functions that each take two double values which represent the two smaller sides of a right triangle. The first will calculate and return the area of the triangle, the second will calculate and return the length of the hypotenuse and the third will calculate and return the perimeter of the triangle. (Note: to calculate the perimeter, you need the value of the hypotenuse, so you must be calling that method from inside the other method.)...
Stack Time Limit : 1 sec, Memory Limit : 131072 KB English / Japanese   Reverse Polish...
Stack Time Limit : 1 sec, Memory Limit : 131072 KB English / Japanese   Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free. Write a program which reads an expression in the Reverse Polish notation and...
write a program to make scientific calculator in java
Problem StatementWrite a program that uses the java Math library and implement the functionality of a scientific calculator. Your program should have the following components:1. A main menu listing all the functionality of the calculator.2. Your program should use the switch structure to switch between various options of the calculator. Your Program should also have the provision to handle invalidoption selection by the user.3. Your calculator SHOULD HAVE the following functionalities. You can add any other additional features. PLEASE MAKE...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT