Simple Java program to calculate expression written in Reverse Polish Notation.

import java.util.Stack;

// 2018 TheFlyingKeyboard and released under MIT License 
// theflyingkeyboard.net
public class Main {
    public static void main(String[] args) {
        String expression = "5 4 + sqrt "; //Note that there must be a space (' ') at the end of the expression to work properly.
        Stack<Double> values = new Stack<Double>();

        int lastSpace = 0;
        double secondValue = 0;
        String item;

        for(int i = 0; i < expression.length(); ++i){
            if(expression.charAt(i) == ' '){
                item = expression.substring(lastSpace, i);
                item = item.replaceAll("\\s+", "");

                if(item.equals("+")){
                    values.push(values.pop() + values.pop());
                }else if(item.equals("-")){
                    secondValue = values.pop();
                    values.push(values.pop() - secondValue);
                }else if(item.equals("*")){
                    values.push(values.pop() * values.pop());
                }else if(item.equals("/")){
                    secondValue = values.pop();
                    values.push(values.pop() / secondValue);
                }else if(item.equals("sqrt")){
                    values.push(Math.sqrt(values.pop()));
                }else{
                    values.push(Double.parseDouble(item));
                }

                lastSpace = i;
            }
        }

        System.out.println(values.peek());
    }
}

 



Java Reverse Polish Notation Calculator
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close