943,031 Members | Top Members by Rank

Ad:
  • Java Code Snippet
  • Views: 25995
  • Java RSS
0

Infix to Postfix

by on Mar 1st, 2009
I have seen several posters asking for help on programs converting an Infix expression to a Postfix one. I have written a program to convert a simple Infix expression to a Postfix one so that people here can be directed towards some sample code from which they get the idea to writing one. I have also provided comments describing what the code part is supposed to do in that block, the idea here is to discourage blind copying and to encourage the understanding of the program. Once the idea behind such a program is undestood, even a beginner can write one for himself.
There can be many ways in which a particular solution can be implemented, this impementation is based on this text.
Lastly I want to mention why I call this program one that converts a simple Infix expression. Thats because I haven't written it to take into consideration complex expressions with paranthesis in them, also I haven't written it for an exhaustive list of operators (the operators I have taken into account are mentioned in the source code). Programmers can take an hint from this simple program and add their own additions to it.
Java Code Snippet (Toggle Plain Text)
  1. package alok.examples;
  2.  
  3. import java.util.Scanner;
  4. import java.util.Stack;
  5.  
  6. /*
  7.  * This is a code snippet to convert a simple Infix Expression to a Postfix one.
  8.  * NOTE : It would not work for expressions containing paranthesis. It only takes into
  9.  * account operators for the following operations:
  10.  * 1. Multiplication
  11.  * 2. Division
  12.  * 3. Modulus
  13.  * 4. Addition
  14.  * 5. Subtraction
  15.  *
  16.  * The precedence of the operations is shown below. Lower level operations have a higher
  17.  * precedence, so here, operations in Level 1 have higher precedence than those mentioned
  18.  * in Level 2.
  19.  * Operations mentioned in the same level have equal precedence.
  20.  *
  21.  * Level 1. Multiplication, Division, Modulus
  22.  * Level 2. Addition, Subtraction
  23.  */
  24. public class Infix2Postfix {
  25.  
  26. private Stack<String> stack;
  27. private String infixExp;
  28. private String postfixExp = "";
  29.  
  30. public Infix2Postfix(String exp){
  31.  
  32. String str = "";
  33. infixExp = exp;
  34. stack = new Stack<String>();
  35.  
  36. for (int i=0;i<infixExp.length();i++){
  37. /*
  38. * If the character is a letter or a digit we append it to the postfix
  39. * expression directly.
  40. */
  41. str = infixExp.substring(i,i+1);
  42. if(str.matches("[a-zA-Z]|\\d"))
  43. postfixExp += str;
  44. else if (isOperator(str)){
  45. /*
  46. * If the stack is empty we directly push the current char into it.
  47. */
  48. if (stack.isEmpty()){
  49. stack.push(str);
  50. }
  51. else{
  52. /*
  53. * If the current character is an operator, we need to check the stack
  54. * status then, if the stack top contains an operator with lower
  55. * precedence, we push the current character in the stack else we pop
  56. * the character from the stack and add it to the postfix string. This
  57. * continues till we either find an operator with lower precedence in the
  58. * stack or we find the stack to be empty.
  59. */
  60. String stackTop = stack.peek();
  61. while (getPrecedence(stackTop,str).equals(stackTop)&& !(stack.isEmpty())){
  62. postfixExp += stack.pop();
  63. if (!(stack.isEmpty()))
  64. stackTop = stack.peek();
  65. }
  66. stack.push(str);
  67. }
  68. }
  69. }
  70. // In the end just append all the operators from the stack to the postfix expression.
  71. while(!(stack.isEmpty()))
  72. postfixExp += stack.pop();
  73. // Print out the postfix expression
  74. System.out.println("The postfix form of the expression you entered is: " + postfixExp);
  75. }
  76.  
  77. /*
  78. * Returns true if 'ch' is an operator, false o/w
  79. */
  80. private boolean isOperator(String ch){
  81.  
  82. String operators = "*/%+-";
  83. if (operators.indexOf(ch) != -1)
  84. return true;
  85. else
  86. return false;
  87. }
  88.  
  89. /*
  90. * Returns the operator with higher precedence among 'op1' & 'op2', if they have equal
  91. * precedence, the first operator in the argument list (op1) is returned.
  92. */
  93. private String getPrecedence(String op1, String op2){
  94.  
  95. String multiplicativeOps = "*/%";
  96. String additiveOps = "+-";
  97.  
  98. if ((multiplicativeOps.indexOf(op1) != -1) && (additiveOps.indexOf(op2) != -1))
  99. return op1;
  100. else if ((multiplicativeOps.indexOf(op2) != -1) && (additiveOps.indexOf(op1) != -1))
  101. return op2;
  102. else if((multiplicativeOps.indexOf(op1) != -1) && (multiplicativeOps.indexOf(op2) != -1))
  103. return op1;
  104. else
  105. return op1;
  106. }
  107.  
  108. public static void main(String[] args){
  109.  
  110. System.out.println("Enter an expression in the Infix form:");
  111. Scanner scanner = new Scanner(System.in);
  112.  
  113. String expression = scanner.nextLine();
  114. new Infix2Postfix(expression);
  115. }
  116. }
Comments on this Code Snippet
Mar 7th, 2011
0

Re: Infix to Postfix

Exception in thread "main" java.lang.NoClassDefFoundError: Infix2Postfix (wrong
name: alok/examples/Infix2Postfix)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
4)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: Infix2Postfix. Program will exit.
Newbie Poster
apc00008 is offline Offline
1 posts
since Mar 2011
Mar 7th, 2011
0

Re: Infix to Postfix

@apc00008, that is because you just copied and pasted code without checking actual code. Otherwise you would have spotted there is package alok.examples; You have two options:
A)Observe package requirement and create relevant folder structure
B)Remove package from start of program
Code tags enforcer
peter_budo is offline Offline
6,649 posts
since Dec 2004
Message:
Previous Thread in Java Forum Timeline: Java file uploader (mostly server side) for multi big files
Next Thread in Java Forum Timeline: javassist annotations





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC