Infix to Postfix Converter

Hello,
I have the following code and it works fine. The converter works correctly but only if there is a space between the characters; therefore, it can't handle inputs with multiple digits (e.g., 34).
How can I modify this code so that there does not have to be a space between each character.
Example:
Currently the program will only run if there is a space between input character. Example: ( 5 * 2 ) / ( 2 * 1 )
However, the program should be able to handle expressions like: (300+23)*(43-21)/(84+7) -- see, with multiple digit numbers like 300
Thank you.
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class ExpressionEvaluator
     // initialize two stacks: operator and operand
     private static Stack operatorStack = new Stack();
     private static Stack operandStack = new Stack();
     // method converts infix expression to postfix notation
     private static String toPostfix(String infix)
          StringTokenizer s = new StringTokenizer(infix);
          // divides the input into tokens for input
          String symbol, postfix = "";
          while (s.hasMoreTokens())
          // while there is input to be read
               symbol = s.nextToken();
               // if it's a number, add it to the string
               if (Character.isDigit(symbol.charAt(0)))
                    postfix = postfix + "" + (Integer.parseInt(symbol));
               else if (symbol.equals("("))
               // push "("
                    Character operator = new Character('(');
                    operatorStack.push(operator);
               else if (symbol.equals(")"))
               // push everything back to "("
                    while (((Character)operatorStack.peek()).charValue() != '(')
                         postfix = postfix + " " + operatorStack.pop();
                    operatorStack.pop();
               else
               // print operatorStack occurring before it that have greater precedence
                    while (!operatorStack.empty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
                         postfix = postfix + " " + operatorStack.pop();
                    Character operator = new Character(symbol.charAt(0));
                    operatorStack.push(operator);
          while (!operatorStack.empty())
               postfix = postfix + " " + operatorStack.pop();
          return postfix;
     // method evaulates postfix expression
     private static int evaluate(String postfix)
          StringTokenizer s = new StringTokenizer(postfix);
          // divides the input into tokens for input
          int value;
          String symbol;
          while (s.hasMoreTokens())
               symbol = s.nextToken();
               if (Character.isDigit(symbol.charAt(0)))
               // if it's a number, push it onto stack
                    Integer operand = new Integer(Integer.parseInt(symbol));
                    operandStack.push(operand);
               else // if it's an operator, operate on the previous two popped operandStack items
                    int op2 = ((Integer)operandStack.pop()).intValue();
                    int op1 = ((Integer)operandStack.pop()).intValue();
                    int result = 0;
                    switch(symbol.charAt(0))
                         case '*': {result = op1 * op2; break;}
                         case '+': {result = op1 + op2; break;}
                         case '-': {result = op1 - op2; break;}
                         case '/': {result = op1 / op2; break;}
                         case '%': {result = op1 % op2; break;}
                    Integer operand = new Integer(result);
                    operandStack.push(operand);
          value = ((Integer)operandStack.pop()).intValue();
          return value;
     // method compares operators to establish precedence
     private static int prec(char x)
          if (x == '+' || x == '-')
               return 1;
          if (x == '*' || x == '/' || x == '%')
               return 2;
          return 0;
     public static void main(String args[]) throws IOException
          String infix;
          // Enter an infix equation option
          infix = JOptionPane.showInputDialog(null, "Enter an Infix Expression:");
          // displays the postfix answer
          JOptionPane.showMessageDialog(null, "Converted to a Postfix Expression: " + toPostfix(infix));
          // Evaluates the expression
          JOptionPane.showMessageDialog(null, "The answer is: " + evaluate(toPostfix(infix)));
}

babypurin wrote:
Currently the program will only run if there is a space between input character. Example: ( 5 * 2 ) / ( 2 * 1 )However, the program should be able to handle expressions like: (300+23)*(43-21)/(84+7) -- see, with multiple digit numbers like 300... I'm still working on an actual answer... I just thought I'd "fix" the question with some strategically placed code tags... The dratted forum software uses common arithmetic operators as markup, which (IMHO) causes a lot more trouble than it's worth.

Similar Messages

  • Infix to postfix printing out incorrectly sometimes..any ideas?

    alright, my program this time is to make an infix to postfix converter.
    I have it coded, and it works fine except when I use parenthesis. I'm supposed to test it with these expressions:
    a + b
    a * b + c
    a * ( b + c )
    a + b * c - d
    ( a + b ) * ( c - d )
    a - ( b - ( v - ( d - ( e - f ))))
         // initialize two stacks: operator and operand
         private Stack operatorStack = new Stack();
         private Stack operandStack = new Stack();
         // method converts infix expression to postfix notation
         public String toPostfix(String infix)
              StringTokenizer s = new StringTokenizer(infix);
              // divides the input into tokens for input
              String symbol, postfix = "";
              while (s.hasMoreTokens())
              // while there is input to be read
                   symbol = s.nextToken();
                   // if it's a number, add it to the string
                   if (Character.isDigit(symbol.charAt(0)))
                        postfix = postfix + " " + (Integer.parseInt(symbol));
                   else if (symbol.equals("("))
                   // push "("
                        Character operator = new Character('(');
                        operatorStack.push(operator);
                   else if (symbol.equals(")"))
                   // push everything back to "("
                        /** ERROR OCCURS HERE !!!! **/
                                 while (((Character)operatorStack.peek()).charValue() != '(')
                             postfix = postfix + " " + operatorStack.pop();
                        operatorStack.pop();
                   else
                   // print operatorStack occurring before it that have greater precedence
                        while (!operatorStack.isEmpty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
                             postfix = postfix + " " + operatorStack.pop();
                        Character operator = new Character(symbol.charAt(0));
                        operatorStack.push(operator);
              while (!operatorStack.isEmpty())
                   postfix = postfix + " " + operatorStack.pop();
              return postfix;
    // method compares operators to establish precedence
         public int prec(char x)
              if (x == '+' || x == '-')
                   return 1;
              if (x == '*' || x == '/' || x == '%')
                   return 2;
              return 3;
    /** MY STACK **/
    import java.util.LinkedList;
    public class StackL {
      private LinkedList list = new LinkedList();
      public void push(Object v) {
        list.addFirst(v);
      public Object peek() {
        return list.getFirst();
      public Object pop() {
        return list.removeFirst();
      public boolean isEmpty()
          return (list.size() == 0);
    }weird, it erased my question/errors I put in...
    When I use any of the expressions with parenthesis (except the 2nd to last one) I get an emptystackexception pointing to the area noted in the code.
    When I test the 2nd to last one (the one I would expect it to give me the most trouble) it prints out an answer, but it is incorrect. It prints out this : "Expression in postfix: a ( b - ( c - ( d - ( e - f ) -" which is incorrect, as it hsould have no parenthesis
    Edited by: Taco_John on Apr 6, 2008 12:46 PM
    Edited by: Taco_John on Apr 6, 2008 12:47 PM
    Edited by: Taco_John on Apr 6, 2008 12:49 PM

    the algorithm we were told to use is here:
    While not stack error and not the end of infix expression
    a.) Extract the next input token from the infix expression (can be constant value, variable, arithmetic operator, left or right parenthesis)
    b.) If token is
    - left parenthesis : push it onto the stack
    - right parenthesis : pop and display stack elements until the left parenthesis is popped (don't sisplay right parenthesis). It's an error if stack becomes empty with no matching right parenthesis found.
    - Operator : if the stack is empty or token is higher priority than the top element, push it onto the stack. Otherwise, pop and display the top stack element and repeat comparison of token with new top element
    Note : left parenthesis in the stack is assumed to have a lower priority than any operator.
    - operand : display it
    When the end of the infix expression is reached, pop and display remaining stack elements until it is empty.
    it works fine on anything without a parenthesis, and it prints an answer (however it is incorrect) for the a - (b-(c-(d-(e-f)))) expression.
    still looking for an idea if I can get one
    Ok, I just noticed this. If i do a * ( b + c ) I get the error. But if I type " a * ( ( b + c ))" with spaces between the left parenthesis and adding an extra parenthesis as well, and NOT spacing the right parenthesis, I get a result that works just like that 2nd to last was doing. So it's something about the spaces...The answer is incorrect when I use the parenthesis as well. So it's not ignoring white space correctly for some reason and it's printing incorrect answers when I use parenthesis.

  • Sample progran of converting infix to postfix

    greetings to each and everyone of us..i need help about my problem in data structures. i need samples of converting infix to postfix.if u have any ideas regarding dis matter plz do reply me..thanks so much.

    What are you talking about?

  • Converting Infix to Postfix

    I have to convert infix to postfix using a stack, and I have no idea where to start. Any suggestions?

    Read the assignment text well, send email to your instructor about that parts that are not clear, and start doing it. Only when you encounter a problem that you can't overcome by reading your notes, the Java tutorial, or the documentation of standard classes come back here and ask a specific question with a clear description of the problem you are having with some source code, what you want it do, what it is doing instead, and possible error message.
    Java tutorial: http://java.sun.com/docs/books/tutorial/
    Documentation of standard classes: http://java.sun.com/j2se/1.5.0/docs/api/
    Examples of how to use them: http://javaalmanac.com

  • Infix to Postfix calculation: having problems.. help?

    This is a program that when you input infix expression, it converts it to postfix expressions the evaluates the postfix..
    I'm having difficulty in my main method. How do i loop it? when the user wants to another input an expression?..
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class Calculator {
         private static Stack operators = new Stack();
         private static Stack operands = new Stack();
         private static int precedence( char operator ) {
              if (operator == '+' || operator == '-' )
                 return 1;
              else if (operator == '*' || operator == '/' || operator == '%')
                  return 2;
              return 0;
         private static String convertToPostfix( String infix ) {
         StringTokenizer input = new StringTokenizer( infix );
         String symbol;
         String postfix = "";     
         while (input.hasMoreTokens()) {          
             symbol = input.nextToken();     
              if (Character.isDigit(symbol.charAt(0))){
                  postfix = postfix + " " + (Integer.parseInt(symbol));     
              }else if (symbol.equals("(")){ 
                   Character isOperator = new Character('(');
                   operators.push( isOperator );
              }else if (symbol.equals(")")) {
                   while (((Character)operators.peek()).charValue() != '(') {
                       postfix = postfix + " " + operators.pop();
                   }operators.pop();
              } else {
                   while (!operators.empty() && !(operators.peek()).equals("(") && precedence(symbol.charAt(0)) <= precedence(((Character)operators.peek()).charValue()))
                        postfix = postfix + " " + operators.pop();
                        Character isOperator = new Character(symbol.charAt(0));
                        operators.push( isOperator );
              while (!operators.empty())
                   postfix = postfix + " " + operators.pop();
                        return postfix;
         private static int evaluate( String postfix ) {
         StringTokenizer input2 = new StringTokenizer( postfix );
         int value;
         String symbol;
         while (input2.hasMoreTokens()) {
             symbol = input2.nextToken();
              if (Character.isDigit(symbol.charAt(0))) {
                  Integer isOperand = new Integer(Integer.parseInt(symbol));
                   operands.push( isOperand );
              }else{
                   int op2 = ((Integer)operands.pop()).intValue();
                   int op1 = ((Integer)operands.pop()).intValue();
                   int result = 0;
                        switch(symbol.charAt(0)){
                             case '*': result = op1 * op2;
                                            break;
                             case '+': result = op1 + op2;
                                            break;
                             case '-': result = op1 - op2;
                                            break;
                             case '/': result = op1 / op2;
                                            break;
                             case '%': result = op1 % op2;
                                            break;
                        Integer isOperand = new Integer(result);
                        operands.push( isOperand );
              value = ((Integer)operands.pop()).intValue();
              return value;
         public static void main(String args[]) throws IOException {
                     JOptionPane.showMessageDialog(null,  "Hello user! I hope you have a wonderful time using the
                        calculator.  = ]"  , "Welcome", JOptionPane.PLAIN_MESSAGE);     
                  JOptionPane.showMessageDialog(null,  "Note: Enter Infix expressions with spaces in between.",
                        "Welcome", JOptionPane.PLAIN_MESSAGE);
                  String infix = JOptionPane.showInputDialog("Enter Mathematical Expression Here: ");
                  String output = "The expression in Postfix is: " +  convertToPostfix(infix);
                  JOptionPane.showMessageDialog(null, output);
                  String answer = "The answer to the equation:  " + evaluate(convertToPostfix(infix));
                  JOptionPane.showMessageDialog(null, answer);
                       String options[] = {"Yes","No",}
                   int option = JOptionPane.showOptionDialog(null,"Do you want evaluate an expression?", "Calculator",  
                       JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,options,options[0]); 
                  JOptionPane.showMessageDialog(null,  "Thank you for using the calculator.\n Have a nice day!  = ]");
    }

    Don't waste people's time by posting your question in more than one forum, please.
    Continued here: [http://forums.sun.com/thread.jspa?threadID=5333073]

  • Infix to postfix expression

    Hi all!
    I'm currently trying to finish up an assignment that is due in a few hours. Here's my delimma, according to the text book and the professor the following algorithm to convert an infix to postfix is as follows:
    1. Two stacks will be used in the conversion(expressionStack and operatorStack)
    2. if an operand is encountered, push onto expressionStack
    3. if an operator is encountered, including the "(" push onto the temporary stack
    4. if a ")" is encountered, pop each operator off the temporaryStack and push it into the expressionStack until a "(" is encountered in the temporaryStack. Once a "(" is encountered, pop that off the temporaryStack.
    Traverse through the infix expression until the end is reached then pop everything from the temporaryStack onto the expression stack.
    Here's the code I wrote for it:
    public String convertInfixToPostfix() throws PostfixConversionException {
      //if there is an unbalace set of parenthesis, throw exception
        if(!isBalance()) {
          throw new PostfixConversionException("Unable to convert infix expression");
        for(int i = 0; i < this.infixExpression.length(); i++) {
          char ch = this.infixExpression.charAt(i);
          //if ch is an operand, push onto stack
          switch(ch) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            this.expressionStack.push("" + ch);
            break;
            //if ch is an operator or a '(', push onto temporaryOperator stack
            case '+':
            case '-':
            case '*':
            case '/':
            case '%':
            case '(':
              this.temporaryOperator.push("" + ch);
              break;
            /*if ch is ')' push all operators from temporaryOperator stack onto expressionStack until
             * until a matching '(' is encountered*/
            case ')':
              //while the top does not equal "(" pop everything off temporaryOperator stack and onto expression stack until a '(' is encountered
              while(!"(".equals(this.temporaryOperator.top())) {
                this.expressionStack.push(this.temporaryOperator.pop());
              //removes one open matching '('
              this.temporaryOperator.pop();
              break;
            default:
              System.out.println("Unable to converted due to invalid characters entered");
              break;
        //while expressionStack is not empty, push everything into temporaryOperator stack
        while(!this.expressionStack.isEmpty()) {
          this.temporaryOperator.push(this.expressionStack.pop());
        while(!this.temporaryOperator.isEmpty()) {
          this.postfixExpression = this.postfixExpression + this.temporaryOperator.pop();
        return this.postfixExpression;
      }The problem is, unless I did the code wrong (which I don't think i did), the method incorrectly converts the infix to the postfix expression. Meaning the algorithm provided by the text book and professor is incorrect. Are there other ways of converting an infix to postfix expression?

    Well using 2 stacks is same as 1 stack and 1
    StringBuffer. So I'd get rid of your temporary stack.
    Tokens either get pushed onto the operator stack or
    postfix stack.I wish I could get rid of the temporary stack and use a StringBuffer, but the professor wants two stacks used.
    Brackets are only slightly more difficult. If you
    have opening bracket, simply push it onto the
    operator stack. If you have a closing bracket pop
    tokens off the operator stack onto the postfix stack
    until you encounter an opening bracket then you
    simply pop it off the stack and discard it.So basically what you're saying is exactly what my code is doing, only with two stacks. However it only works if the infix entered has to do only one operations like 4-8 or 8+3, etc..but when it converts a longer expression like 0-(((7-8+3*(9/1)*2)+5)*6), postfix is 078391/2**-56*- and result is 300. but when I entered the infix in a calculator, the result is -384. I check my compute method and Im pretty sure that is correct. So that leaves the conversion method. In any case heres the compute method, I might be wrong, but I'm pretty sure I got that down.
    1. when a operand is encountered, push it into stack
    2. when an operator is encountered, pop two operands off and compute, then push it back into the stack.
    public double computeResult(String postfix) throws PostfixArithmeticException {
        //local variables
        Stack computePostfix = new Stack();
        int countOperators = 0;
        int countOperands = 0;
        //goes through the postfix and determines number of operators and operands
        for(int i = 0; i < postfix.length(); i++) {
         char ch = postfix.charAt(i);
         if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%') {
           countOperators++;
         else
           countOperands++;
        //test if there are enough operators and operands, number of operators should be 1 less than operands
        if((countOperators + 1) != countOperands || postfix.length() == 1) {
          //throw PostfixArithmeticException if there are not enough operators or operands
          throw new PostfixArithmeticException("Unable to compute postfix expression.");
        //otherwise, compute postfix expresstion
        for(int i = 0; i < postfix.length(); i++) {
          char ch = postfix.charAt(i);
          //if the character is not a operator, push onto a stack
          if(ch != '+' && ch != '-' && ch != '*' && ch != '/' && ch != '%') {
            computePostfix.push("" + ch);
          //otherwise, if an operator, pop two operands off the stack, compute with operator and push back on stack
          else {
            double operand2 = Double.parseDouble("" + computePostfix.pop());
            double operand1 = Double.parseDouble("" + computePostfix.pop());
            switch(ch){
              case '+':
                this.result =  operand1 + operand2;
                break;
              case '-':
                this.result =  operand1 - operand2;
                break;
              case '*':
                this.result =  operand1 * operand2;
                break;
              case '/':
                this.result =  operand1 / operand2;
                break;
              case '%':
                this.result =  operand1 % operand2;
                break;
            computePostfix.push("" + result);
        //return the result of the computation
        this.result = Double.parseDouble("" + computePostfix.pop());
        return result;
      }Also, I've tested that there should be the correct number of operators to an operand (which is the number of operators is always one less than number of operands)

  • Infix to postfix algorithm

    I need som help to finish my algoritm.
    This is what I have so far:
    import java.util.Stack;
    import javax.swing.*;
    public class InfixToPostfix {
         public static void main(String[] args) {
              Object slutt      = "#";
              char[] operator      = {'^','*','/','+','-'};
              char vParentes      = '(';
              char hParentes      = ')';
              char[] uOperator      = {'^','*','/','+','-','('};
              char[] opPri      = {'^','*','/','+','-','(',')','#'};
              int [] infixPri      = { 3 , 2 , 2 , 1 , 1 , 4 , 0 , 0 };
              int [] opStackPri      = { 3 , 2 , 2 , 1 , 1 , 0 ,-1 , 0 };
              String infixStr      = JOptionPane.showInputDialog("infix : ");
              infixStr           += slutt;
              String postfixStr     = "";
              System.out.println("Infix: "+infixStr);
              Stack stack = new Stack();
              System.out.println ("Stack is empty: "+stack.empty ());
              char c;
              for (int i=0; i<infixStr.length(); i++) {
                   c = infixStr.charAt(i);
                   if (c == '+' || c == '-' || c == '*' || c == '/') {
                        if (stack.empty()) {
                             stack.push(String.valueOf(c));
                        else {
                             // HELP WANTED!!!!!
                   else if (c == '#') {
                        System.out.println("Postfix: "+ postfixStr);
                        System.exit(0);
                   else {
                        postfixStr += c;
    In the "help wanted" else-loop I want to do the following:
    The operator from stack should pop, and
    it must be compared with the next operator
    from the infix-expression, in according to the
    priority which is given in the opPri, infixPri and opStackPri.
    The if the infix-operator has a higher priority then I push it
    to the stack, else the stack-operator pops and are added
    to the postfix-string, and the next stack operator is popped and
    compared with the same infix-operator. Then again if the infix has
    a higher value I push it to the stack, else the stack-operator is popped
    and added. So on and so on...
    As you see, I know how it should function, but I am not sure at all
    about the syntax. Can anyone please help me with this?
    thanks!
    torvald helmer

    Hi there, firstly im not sure why u have done infixPri and opStackPri, i dont think those are necessary?? I have implemented an infix to postfix algorithm that uses only these operators : + - / *. From the help wanted part what you'd want to do is to do this: while the stack is not empty and a '(' character is not encountered, operators of greater or equal precedence from the stack will be popped then appended to the postfixExp else stop the while. Once the while is finished then u push infix onto the stack. Hope this helps. Cheers

  • Infix to Postfix - Please help

    Hello everybody...i am new in java...and i thing i messed up with my exercise. Can anyone help? I have to prepare a main class that translates infixes to postfixes. i have done this until now:
    import java.util.*;
    import jss2.*;
    import java.io.IOException;
    import java.util.Stack;
    public class a3
         private Stack theStack;
         private String input;
         private String output = "";
         public a3(String in)//Constructor for a3 class
         String input = in;
         int stackSize = input.length();
         theStack = new Stack(stackSize);
         public static void main(String[] args) throws IOException
         String input = "1+2*4/5-7+3/6";
         String output;
         System.out.println("- The program translates the InFix to PostFix");
         System.out.println("- The format that you have to enter is: ");
         System.out.printf("(X+Y)*(Z-I) or similar expressions with numbers");
         System.out.println();
         a3 Trans = new a3(input);
         output = Trans.Postfix();
         System.out.println("Postfix is " + output + '\n');
    i have entered in the same package the classes: Postfix.java, LinkedStack.java, PostfixEvaluator.java and StackADT.java
    Please can anyone help me somehow??????

    Please have a look here
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=5217005
    and here
    http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm
    for a general explanation of the algorithm you need.
    Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;Other sites to look at:
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5157105
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=778333
    http://onesearch.sun.com/search/onesearch/index.jsp?charset=utf-8&col=community-all&qt=infix+postfix&y=0&x=0&cs=false&rt=true
    ps: don't pay bogad, he's a cheating sob and will rob you blind. We'll help you here for free.
    good luck, pete
    Edited by: petes1234 on Nov 10, 2007 11:40 AM

  • Help! - code for infix to postfix

    can someome please send me the code for infix to postfix?
    thanks

    Or--and I know this will sound crazy, but just keep an open mind--you could try doing your homework yourself, and then post your attempt here when you get stuck, along with details of what specific problems you are having.
    If you are unwilling or unable to do that, then you should look elsewhere. This site is not a place to get code written for you. Try finding someone who will do it for money.

  • Code for infix to postfix

    plz send me infix to postfix code in java soon.

    plz send me infix to postfix code in java soon.I've intercepted all transmissions. Any code sent to
    you has been redistributed to various parts of the
    internet at random. You'll have to go find it
    yourself (using one of the common search engines).You forgot the "All your base are belong to us!" statement...

  • Recursive Infix to Postfix algorithm (Shunting-yard algorithm)

    Hi, I have to write a Infix to Postfix algorithm in a recursive form. I have an idea of how to do it iteratively using a Stack, but recursively I'm having some trouble. Could anybody offer some help or hints on how to get started?

    Well, I could write the iterative version along the lines of this:
    Scanner inScan = new Scanner(System.in);
    String exp;
    StringBuffer postfix = new StringBuffer();
    Stack stk = new Stack<Character>();
    System.out.println("Enter an arithmetic expression: ");
    exp = inScan.nextLine();
    for(int i = 0; i<exp.length(); i++)
        char ch = exp.charAt(i);
        if(ch<='F' && ch>='A')
            stk.push(ch);
        else{
           switch(ch)
              case '+':       \\what to do if ch is a + operator
              case '*':        \\what to do if ch is a * operator
              case '(':        \\what to do if ch is a (
              // and so on for each operator or paranthesis, i know what to do with each operator
    }That's not the full program obviously and may have some mistakes, but I'm confident I know how to do it iteratively. Recursively is the problem. What kind of base case could I use for my recursive method? And do I need more than one recursive method?

  • Convert infix to postfix

    i need a reply fast... i have been trying to convert infix to post fix in java.... but i cant get the output. The program just print the same input....i cant get output
    heres my code
    import java.util.Scanner;
    import java.io.*;
    import java.util.*;
    public class Infix{
         public static void main( String[] args){
              Scanner scan=new Scanner(System.in);
              Stack<String> stack = new Stack<String>();
              System.out.println(" enter infix");
              String s=scan.next();
              while (!s.equals(0)){
                   String postfix="";
                   if ( s.equals("+")) stack.push(s);
                   else if ( s.equals("-")) stack.push(s);
                   else if ( s.equals("*")) stack.push(s);
                   else if ( s.equals("/")) stack.push(s);
                   else if ( s.equals("(")) System.out.print("");
                   else if ( s.equals(")")) System.out.print(stack.pop()+"");
                   System.out.println("postfix");
                   //System.out.print(s);// I DONT KNOW HOW TO ADD ALL THE VARIABLES INTO A SEPERATE STRING
         System.exit(1);
    Edited by: boygenius on Sep 16, 2007 3:04 PM

    http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm
    I have found the above site has a great explanation of how to perform the conversion. Basically you will need a Stack to push/pop your operators as well as a String/StringBuffer/StringBuilder to build the postfix expression.

  • Infix to Postfix application

    I have to check if the input message is balanced ( only () [] {} ) then i have to check anothe rinput message and make sure its infix, then convert it to postfix, and thats where my problem is, i seem to have everything, but i cant get around this SyntaxErrorException, im not sure how to get it to work, i feel like im missing a very small part, any ideas ? The catch block with the syntaxerrorexception cannot find the symbol, and yes it is already defined in another class,
    import java.util.*;
    import java.util.Stack;
    import java.util.EmptyStackException;
    import javax.swing.JOptionPane;
    public class ParentheseApp {
    public static void main(String args[])     {
    String newText = JOptionPane.showInputDialog("Enter a Mathematical expression");
    ParenChecker theParenthese = new ParenChecker();
    oolean test = theParenthese.isBalanced(newText);          
    if (test = true) {
    /IF public STATIC boolean was not called in the parenchecker
    //class then i would have to call the method
    if(ParenChecker.isBalanced(newText)) {
    JOptionPane.showMessageDialog(null, newText + "is balanced");
         else
    JOptionPane.showMessageDialog(null, newText + "is not balanced");
    String infix = JOptionPane.showInputDialog("Eneter an infix expression");
    InfixToPostfixParens theIntoPost = new InfixToPostfixParens();
    if(ParenChecker.isBalanced(infix)) {
    JOptionPane.showMessageDialog(null, infix + "is balanced");
         else
    JOptionPane.showMessageDialog(null, infix + "is not balanced");
         while(ParenChecker.isBalanced(infix)) {
    JOptionPane.showMessageDialog(null, infix + "is balanced");
              try {
         String postfix = theIntoPost.convert(infix);
    JOptionPane.showMessageDialog(null, "Infix expression " +
         infix + "converts to" + postfix);
    catch (SyntaxErrorException e) {
    JOptionPane.showMessageDialog(null, e.getMessage());
              }

    wpafbuser1 wrote:
    huh? balanced? infix? care to elaborate on these?I believe infix refers to infix notation: "(a + b) * c". Postfix would be "a b + c *". Balancing would be whether the parentheses in the infix notation are matched.
    However, there's no code of any significance to this problem in OP's post.
    EDIT: I think postfix is sometimes called RPN (reverse polish notation).
    Edited by: paul.miner on Dec 13, 2007 3:14 PM

  • Infix to PostFix

    hi,
    I have an infix format as shown below, i need to know how does this logical infix expression can be converted in to postfix expression.
    How do v specify the IF THEN ELSE of the expression in the postfix expression.
    IF:VarX :> :123 :THEN :VarY := :234 :+ :VarSAM :EIF
    Thanks in advance..

    the question as you have asked it has no answer. It is a bit like saying, "I want to travel to a foreign land, How do you say 'Hello'"
    The problem is that you have not specified any language.
    In-fix and post-fix simply refer to two different ways of writing out trees (and the use of the term 'infix' strongly implies binary trees at that). In post fix you ouput the value of a parent only after you have output the value of the children of that parent. In in fix you output the parent inbetween its two children (hence the implication of binary trees)
    In the world of mathematical expressions, like you learn in algebra and calculus, there is a well defined and commonly understood structure (that also just happens to be binary for the four main operation +,-,*,/) So it is easy to talk about taking the expression:
    6 + 3*(7 - 5)
    and talk about the postfix form:
    6 3 7 5 - * +
    However when you are talking about parsing a computer expression, you are now talking about general trees and there are numerous different ways that you could structure those trees.
    For example you could think of an IF as a 3 way branching node like this
    IF(boolean, code1, code2)
    or if you want to be binary about it you introduce a new branch node
    IF(boolean, CodePair( code1, code2))
    But nothing prevents you from doing any other wierd thing like perhaps
    ELSEIF( code2, SimpleIF(boolean, code1))
    Needless to say all of these representation are equally valid and all have completely different post fix representations.
    Since you have not defined any underlying tree structure for the code in your example it is not possible to give an answer.
    If your little infix example was in fact derived from a grammer, then you must go back and look at the tree structure that was implied by your grammer and then you could possibly talk meaningfully about a post fix representation of the parse.
    Hope that helps

  • Infix Expression - Postfix Expressions

    Hello
    I have a program that uses 2 stacks (InfixStack and OperatorStack) to evaluate an infix expression that a user inputs. My problem is that i want to also output the postfix form of the infix expression, i know that i need another stack (PostfixStack). I don't know what the algorithm for converting Infix --> Postfix. I would appreciate any help regrading this matter, a description of the algorithum or psdeou code.
    Thanks

    Try these links:
    http://www.cs.uct.ac.za/courses/Course1/116/Tut0/help/inpostalg.html
    http://joda.cis.temple.edu/~koffman/cis223/InfixToPostfix.doc (MS Word DOC)
    This is a really nice paper in PDF:
    http://www.utdallas.edu/~vinod/publications/Prefix.pdf

Maybe you are looking for

  • I had the bottom case of my MacbookPro replaced and now I can't print help?

    Hi I had the bottom case to my Macbook Pro 2.33 Ghz intel core 2 duo replaced. Prior to this the machine worked perfectly. Now it can't connect to the internet using DHCP and it won't print either over the internet or with the printer plugged in dire

  • Using a file backup for a fresh iTunes install?

    Recently the Window 7 system I keep my iTunes music database on died, and won't boot. Fortunately, I have a fresh backup of the system disk on an external drive that was made using the backup software Macrium Reflect. The entire iTunes song database

  • Document bulk upload to content server for SAP-DMS?

    Dear all, Thanx Regards, John.

  • In-Ear Headphones Warranty Question

    My non-Apple headphones are dead - a wire is probably loose at the connector (most common problem I have with headphones). I'm probably going to purchase the Apple In-Ear headphones. Does it come with a one-year warranty? If the cord or connector goe

  • Information on 0CS_ITEM: Item info object

    Hi All, I am trying to build one infocube, in one of the dimensions, i have used characterstic 0CS_ITEM(which is used in cube: 0BCS_C10). When I use this info object to build a dimension, 0BCS_INITEM and 0CS_CHART are automatically adding. I also obs