Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8913297
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T04:25:27+00:00 2026-06-15T04:25:27+00:00

I am currently working with a reverse polish notation calculator. It is fully functional

  • 0

I am currently working with a reverse polish notation calculator. It is fully functional but I am running into issues with text input that will then be used to calculate the values. The program breaks if introduce a formula like ( 8 5 + ) 6 * = . Is there a way to simply ignore any parentheses that show up in the input value? Also my program does split accordingly to space between each number but if I for get to add a space between operands or parentheses it also breaks: (8 5 +)6 * =. If it is an invalid formulas 12 + = ( missing a number) i would like to ignore them and just display in output textBox an error message.

Side Note: every formula is triggered by an ending =.

Code

namespace rpncalc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

      private string inputValue = "";

        private void RPNCalc(string rpnValue)
        {
            Stack<int> stackCreated = new Stack<int>();
            stackCreated.Clear();
            string[] inputArray = rpnValue.Split();
            int end = inputArray.Length - 1;
            int numInput;
            int i = 0;

            do
            {
                if ("=+-*/%^".IndexOf(inputArray[i]) == -1)
                {
                    try
                    {
                        numInput = Convert.ToInt32(inputArray[i]);
                        stackCreated.Push(numInput);
                    }
                    catch
                    {
                        MessageBox.Show("Please check the input");
                    }
                }

                    else if (inputArray[i]== "+")
                    {
                        try
                        {
                            int store1 = stackCreated.Pop();
                            int store2 = stackCreated.Pop();
                            stackCreated.Push(store2 + store1);
                        }
                        catch
                        {
                        }
                    }

                    else if (inputArray[i]== "-")
                    {
                        try
                        {
                            int store1 = stackCreated.Pop();
                            int store2 = stackCreated.Pop();
                            stackCreated.Push(store2 - store1);
                        }
                        catch
                        {
                        }
                    }

                    else if (inputArray[i]== "%")
                    {
                        try
                        {
                            int store1 = stackCreated.Pop();
                            int store2 = stackCreated.Pop();
                            stackCreated.Push(store2 % store1);
                        }
                        catch
                        {
                        }
                    }

                    else if (inputArray[i]== "*")
                    {
                        try
                        {
                            int store1 = stackCreated.Pop();
                            int store2 = stackCreated.Pop();
                            stackCreated.Push(store2 * store1);
                        }
                        catch
                        {
                        }
                    }

                    else if (inputArray[i]== "/")
                    {
                        try
                        {
                            int store1 = stackCreated.Pop();
                            int store2 = stackCreated.Pop();
                            stackCreated.Push(store2 / store1);
                        }
                        catch
                        {
                        }
                    }

                    else if (inputArray[i] == "^")
                    {
                        try
                        {
                            int store1 = stackCreated.Pop();
                            int store2 = stackCreated.Pop();
                            stackCreated.Push((int)Math.Pow(store1, store2));

                        }
                        catch
                        {
                        }
                    }

            }
            while(i++ < end && inputArray[i]!= "=" && stackCreated.Count != 0);
            string result = inputValue + " " + stackCreated.Pop().ToString() + Environment.NewLine;
            TxtOutputBox.AppendText(result);
            TxtInputBox.Clear();

        }

        private void TxtOutputBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void Btn_Calc_Click(object sender, EventArgs e)
        {
            inputValue = TxtInputBox.Text + " ";
            RPNCalc(inputValue);
        }
    }
}

enter image description here

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T04:25:28+00:00Added an answer on June 15, 2026 at 4:25 am

    First of all, doing something like

    rpnValue = rpnValue.Replace(" ", "").Replace("(","").Replace(")","");
    

    as Sam’s answer to this question recommends, would require a major rewrite of the entire algorithm. The problem is with the Replace(” “, “”) part which eliminates spaces. However, the algorithm relies on Split to tokenise the input. If you eliminate spaces before that Split, instead of getting an array of numbers and operators, you will get a single string which cannot be processed by the existing code. Worse still both “12 3 * =” and “1 23 * =” will be converted to “123*=” !!!

    To avoid making big changes change the code as follows:

    Insert the following code before the Split:

    rpnValue = rpnValue.Replace("("," ").Replace(")"," ");
    

    This makes sure sure that parentheses are ignored as requested but in a way that makes (8 5 +)6 * = work.

    And then make the following addition:

                    if (" \t\n\r".IndexOf(inputArray[i]) != -1) {
                           continue;
                    } else if ("=+-*/%^".IndexOf(inputArray[i]) == -1)
                    ...
    

    Also the code at the end of the loop needs to change:

            while (i++ < end && inputArray[i] != "=");
            if(stackCreated.Count != 1)
                MessageBox.Show("Please check the input");
    

    Hope that helps 🙂

    —————————The answer proper ends here ———————————-

    Additional recommendation:
    The question does not cover the issue of error reporting, but there was also something else I noticed: operations on the stack are surrounded by try catch statements and nothing happens in the catch part. This way an ill formatted input is not appropriately flagged. I would recommend deleting those try catch statements and putting a single one around the body of the function.

    Some fun: My aim was to just answer the very specific question asked, but since seeing LB’s beautiful piece of code was posted here, I updated the answer to include an alternative definition of RPNCalc that is just as consise but closer to your original approach which does not rely on regular expressions (except that expressions to be calculated do not end with an =).

        private void RPNCalc(string rpnValue)
        {
            Stack<int> stackCreated = new Stack<int>();
    
            try {
    
                var tokens = rpnValue.Replace("(", " ").Replace(")", " ")
                                     .Split().Where(s => !String.IsNullOrWhiteSpace(s));
    
                foreach (var t in tokens) {
    
                    try {
    
                        stackCreated.Push(Convert.ToInt32(t));
    
                    } catch {
    
                        int store1 = stackCreated.Pop();
                        int store2 = stackCreated.Pop();
    
                        switch(t) {
                            case "+": store2 += store1; break;
                            case "-": store2 -= store1; break;
                            case "*": store2 *= store1; break;
                            case "/": store2 /= store1; break;
                            case "%": store2 %= store1; break;
                            case "^": store2 = (int) Math.Pow(store2, store1); break; /* was (int) Math.Pow(store1, store2); in the original code*/  
                            default: throw new Exception();
                        }
    
                        stackCreated.Push(store2);
                    }
                }
    
                if(stackCreated.Count != 1)
                    MessageBox.Show("Please check the input");
                else
                    textBox1.Text =   stackCreated.Pop().ToString();
    
            } catch {
                MessageBox.Show("Please check the input");
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am a novice C# coder and currently working on a Reverse polish notation
I am currently working with Reverse Polish Notation. I have able to perform all
I am currently working on an application that allows reverse geocoding using silverlight +
Currently working with converting SQLException error messages into messages that are more useful for
Im currently working on a game that uses multi touch to apply zoom to
Am currently working on an application that requires users to submit posts and comments
I am working on an app that will show reverse view from camera. For
I am currently working on a project where I have to read a text
I'm currently working on a system that in some cases will need to run
I've been working with Django for a while now (currently on version 1.2), but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.