Transforming Infix to Postfix in Java: Solving Arithmetic Expressions with RPN

In summary, the conversation discusses creating a class that will transform a basic arithmetic expression from infix to postfix and then evaluate the postfix expression to give the answer. There is a discussion about the operators and their precedence, as well as creating a method to determine which operator has a higher precedence. The conversation also mentions using a syntax diagram and recursive methods to solve the problem. The conversation ends with sharing a clean program in Java for evaluating arithmetic expressions and the difficulties of writing the same program in C. Overall, the emphasis is on finding the best and most efficient way to evaluate arithmetic expressions.
  • #1
muna580
I am creating a class that will transform a basic arithmetic expression from infix to postfix (Reverse Polish Notation (RPN)). Then after then, it will evaluate the postfix expression and give the answer.

I have having a little trouble with the operators (+,-,/,0*, and %). Like, I have to create a method called hasHigherPrecedence(char c1, char c2), which returns a boolean saying where c1 has a higher precedence than c2. But I don't really know hwo to create this method. Can someone help me.
 
Technology news on Phys.org
  • #2
Forget programming for a moment.

If I asked you to tell me which of "+" or "*" had higher precedence, what would you do to figure it out?

What if you had to teach a 10-year hold how to figure it out? How would you do that?
 
  • #3
Umm, I think this is the precedence order from highest to lowest: * / + -. Where does the % go?
 
  • #4
This is homework or an assignment, right?
 
  • #5
Create a syntax diagram and make code to follow it.

http://www.horstmann.com/bigj2/slides/slides18.zip

here is the cleanest program to evaluate an arithmetic expression I have ever seen. Evaluator.java, it took me some time to figure it out exactly but it is worft it.
 
  • #6
You have to definitively look up the operator's precedence orders. Usually this piece of information can be found in the chapter that describe integer operators. Certain operators have identical precedence orders. I would assign an integer precedence level value to each operator.
 
  • #7
muna580 said:
Umm, I think this is the precedence order from highest to lowest: * / + -. Where does the % go?
If you mean the modulus operator in C, it has the same precedence as the '/' operator.

Good luck with the RPN, I might add. I wrote a set of C functions to do that parsing for me once. I'm still not happy with it, and have sunk weeks into it over the course of years (it probably didn't help that I was tryign to do something slightly different with it every time I reopened that particular can of worms).

The cheap and sleazy fix is to get the entire formula into a string, then build a binary tree from it by simply splitting the string on each precedence, with same same precedence from left to right, then splitting each substring on the next precedence, etc. That actually works pretty well. Matched delimiters affecting parsing (e.g., [], (), and "") are messy but not too bad.

The problem arises when you have multiline input. Cheap and sleazy no longer works. Then you have to do it the right way with a stack. That's when it gets messy.

Once you've got the tree, spitting out the RPN is obviously trivial.
 
  • #8
I also had to write the same program in C (parse infix arithmetic expression and print postfix and prefix), I first wrote it in Java took me less than 30 mins, and then I tried to write it in C it took me about 7 hours to do it, I spend 3,5 hours searching for a bug it turned out that I allocated a struct wrongly, I could never have done such a mistake in Java, anyway, I am very pleased with my C program and specially with Java, one way is to do some elaborate substring work but that is a mess, there is an alternative way, you can do it recursively. Make a syntax diagram and follow it recursively, very hard to make a mistake then. Something like that

Code:
 /**
      Evaluates the expression.
      @return the value of the expression.
   */
   public Node getExpressionValue()
   {
      Node value = getTermValue();
      boolean done = false;
      while (!done)
      {
         String next = tokenizer.peekToken();
         if ("+".equals(next) || "-".equals(next))
         {
            tokenizer.nextToken(); // Discard "+" or "-"
            Node value2 = getTermValue();
            if ("+".equals(next)) value = new Node("+", value, value2);
            else value = new Node("-", value, value2);
         }
         else done = true;
      }
      return value;
   }

   /**
      Evaluates the next term found in the expression.
      @return the value of the term
   */
   public Node getTermValue()
   {
      Node value = getFactorValue();
      boolean done = false;
      while (!done)
      {
         String next = tokenizer.peekToken();
         if ("*".equals(next) || "/".equals(next))
         {
            tokenizer.nextToken();
            Node value2 = getFactorValue();
            if ("*".equals(next)) value = new Node("*", value, value2);
            else value = new Node("/", value, value2);
         }
         else done = true;
      }
      return value;
   }

   /**
      Evaluates the next factor found in the expression.
      @return the value of the factor
   */
   public Node getFactorValue()
   {
      Node value;
      String next = tokenizer.peekToken();
      if ("(".equals(next))
      {
         tokenizer.nextToken(); // Discard "("
         value = getExpressionValue();
         tokenizer.nextToken(); // Discard ")"
      }
      else
         value = new Node(tokenizer.nextToken());
      return value;
   }
 

Attachments

  • syntaxDiagrams.gif
    syntaxDiagrams.gif
    8.6 KB · Views: 548
Last edited:

FAQ: Transforming Infix to Postfix in Java: Solving Arithmetic Expressions with RPN

What is the purpose of transforming infix to postfix in Java?

The purpose of transforming infix to postfix in Java is to convert an arithmetic expression written in infix notation (where operators are placed between operands) to postfix notation (where operators are placed after their corresponding operands). This conversion allows for easier evaluation of the expression using Reverse Polish Notation (RPN) and can also help avoid issues with operator precedence and parentheses.

How is the infix to postfix transformation algorithm implemented in Java?

The infix to postfix transformation algorithm in Java can be implemented using a stack data structure. The algorithm involves iterating through the expression and pushing operands onto the stack, while also checking the precedence of operators and popping them onto the output string in the correct order. Once the entire expression has been processed, the remaining operators on the stack are popped onto the output string in the appropriate order.

Can the infix to postfix transformation algorithm handle all types of arithmetic expressions?

Yes, the infix to postfix transformation algorithm can handle all types of arithmetic expressions, including expressions with multiple operators, parentheses, and unary operators. This is because the algorithm is designed to handle operator precedence and can also account for the placement of parentheses in the expression.

What are the advantages of using Reverse Polish Notation (RPN) for evaluating arithmetic expressions?

One advantage of using Reverse Polish Notation (RPN) for evaluating arithmetic expressions is that it eliminates the need for parentheses and operator precedence rules. This makes the expression easier to read and evaluate. Additionally, RPN can also be evaluated using a stack data structure, making it a more efficient method of evaluation.

Is transforming infix to postfix a commonly used technique in Java programming?

Yes, transforming infix to postfix is a commonly used technique in Java programming, especially when working with arithmetic expressions. It is often used in applications that involve mathematical calculations, such as calculators or financial analysis tools. The use of RPN is also prevalent in computer science courses as a way to teach algorithm design and data structures.

Similar threads

Replies
14
Views
4K
Replies
5
Views
2K
Replies
4
Views
5K
Replies
1
Views
39K
Replies
12
Views
3K
Replies
2
Views
4K
Replies
3
Views
2K
Back
Top