InfixTopostfix.

i have this application where you enter a postfix expression and it returns it in infix form. i have it working in the sence that when you enter ( 9 * 9 ) you get back 9 9 * which is the infix form. so now i want to add a new operator say i am using the @ sign to represent a function so my new operator list is "+-*/@()". so i enter something like @date ( 9 + 5 ) + 6 it should be returned in infix form like this 9 5 + @date 6 + but instead my application returns it like this
@date 9 5 + 6 + which is wrong the @date is in the wrong position. i have been trying all day and i cant fix it . Below is the code for the InfixToPostfix. i would appreciate if someone could point out where i am going wrong.
   import java.util.*;
public class InfixToPostfixParens {
  // Nested Class
  /** Class to report a syntax error. */
  public static class SyntaxErrorException
      extends Exception {
    /** Construct a SyntaxErrorException with the specified
        message.
        @param message The message
    SyntaxErrorException(String message) {
      super(message);
  // Data Fields
  /** The operator stack */
  private static Stack operatorStack;
  /** The operators */
  private static final String OPERATORS = "+-*/@()";
  /** The precedence of the operators, matches order of OPERATORS. */
  private static final int[] PRECEDENCE = {
      1, 1, 2, 2, 3, -1, -1};
  /** The postfix string */
  private static StringBuffer postfix;
  /** Convert a string from infix to postfix.
      @param expression The infix expression
      @throws SyntaxErrorException
  static void convert2() throws SyntaxErrorException {
     String infix = Main.InputExpression.getText();
    operatorStack = new Stack();
    postfix = new StringBuffer();
    StringTokenizer infixTokens = new StringTokenizer(infix);
    try {
      // Process each token in the infix string
      // (same as for class InfixToPostfix.
      // Process each token in the infix string.
      while (infixTokens.hasMoreTokens()) {
        String nextToken = infixTokens.nextToken();
        String firstChar = nextToken.substring(0,1);
        // Is it an operand?
        if (Character.isJavaIdentifierStart(firstChar.charAt(0))
            || Character.isDigit(firstChar.charAt(0))) {
          postfix.append(nextToken);
          postfix.append(' ');
        } // Is it an operator?
        else if (isOperator(firstChar)) {
          processOperator(nextToken);
        else {
          throw new SyntaxErrorException
              ("Unexpected Character Encountered: "
               + firstChar);
      } // End while.
      // Pop any remaining operators
      // and append them to postfix.
      while (!operatorStack.empty()) {
        String op = (String) operatorStack.pop();
        // Any '(' on the stack is not matched.
        if (op.equalsIgnoreCase("(") )
          throw new SyntaxErrorException(
              "Unmatched opening parenthesis");
        postfix.append(op);
        postfix.append(' ');
      // assert: Stack is empty, return result.
      String Answer = new String(postfix);
       Main.OutputResult.setText(Answer);
    catch (EmptyStackException ex) {
      throw new SyntaxErrorException
          ("Syntax Error: The stack is empty");
  /** Method to process operators.
      @param op The operator
      @throws EmptyStackException
  private static void processOperator(String op) {
       if (operatorStack.empty() || op == "(") {
           operatorStack.push(op);
    else {
      // Peek the operator stack and
      // let topOp be the top operator.
      String topOp =
           (String) operatorStack.peek();
      if (precedence(op.substring(0,1)) > precedence(topOp.substring(0,1))) {
        operatorStack.push(op);
      else {
        // Pop all stacked operators with equal
        // or higher precedence than op.
        while (!operatorStack.empty()
               && precedence(op.substring(0,1)) <= precedence(topOp.substring(0,1))) {
          operatorStack.pop();
          if (topOp.equalsIgnoreCase("("))  {
            // Matching '(' popped - exit loop.
            break;
          postfix.append(topOp);
          postfix.append(' ');
          if (!operatorStack.empty()) {
            // Reset topOp.
            topOp =
                 (String)
                 operatorStack.peek();
        // assert: Operator stack is empty or
        //         current operator precedence >
        //         top of stack operator precedence.
        if (!op.equalsIgnoreCase(")") )
          operatorStack.push(op);
  /** Determine whether a character is an operator.
      @param ch The character to be tested
      @return true if ch is an operator
  private static boolean isOperator(String ch) {
    return OPERATORS.indexOf(ch) != -1;
  /** Determine the precedence of an operator.
      @param op The operator
      @return the precedence
  private static int precedence(String op) {
    return PRECEDENCE[OPERATORS.indexOf(op)];
}  Message was edited by:
declan156

i understand how it works im just asking is there away of fixing my problem. i am only learning how to program. if you see how its done once you will know how to do it the next time. thats away of learning. I changed the code around a couple of times for instance when i changed the -1's to 4's it displays it correctly except it leaves the right bracket. Then i put in   if (topOp.equalsIgnoreCase(")"))  {
              // Matching '(' popped - exit loop.
              break;
           } this gets rid of the bracket but produces the wrong output
Message was edited by:
declan156

Similar Messages

  • InfixToPostfix..help

    i am trying to write infixToPostfix, this is the algorithm, but some problme here...can anyone check it for me:)
    thanks
    import java.util.*;
    import java.util.Stack;
    public class Compute
         //private String shunt;
       private int a;
       private String[] Shunt;
       private int oppriority;
       private String fff;
       private String  pofix;
          public String infixToPostfix(String exp)
               {  this.oppriority = oppriority;
                   this.fff = exp;
                   Stack shunt = new Stack();
                   String pofix = "";
                  for ( int i=0;i<exp.length();i++)
                      { switch (exp.charAt(i))
                          case "(" : { shunt.push( "(");
                          break;}
                       // case ")" : { while (shunt.top() != ( "(" ))
                           case " ) " : {while (shunt.top() !=  ( " ( " ))
                             {  pofix = pofix+shunt.pop();}
                                exp.pop();
                        break;
              case "+" : case "-": case "*": case "/": case "^" :
           { while((!shunt.isEmpty() &&
                  ((shunt.top()!= '(') &&
                  (oppriority(shunt.top()) >=
                  oppriority(exp.charAt(i))))))
                  { pofix = pofix + shunt.pop();}
                  shunt.push(exp.charAt(i));
                  break;
                default :
              { pofix = pofix + exp.charAt(i);}
            }       // end of switch
              }         // end of for
              while (!shunt.isEmpty())
             { pofix = pofix + shunt.pop(); }
                return pofix;
              }         // end of infixToPostfix
          private int oppriority(char ch)
                { switch (ch)
                { case '+': case '-' : return(1);
                  case '*': case '/' : return(2);
                  case '^': return(3);
                 default : return(4);
    }

    case " ) " : {while (shunt.top() !=  ( " ( " ))
    it can not be  compiled...
    but i dont know what i wrote worng....                                                                                                                                                                                                                                       

  • Keep getting   " identifier expected" error

    I keep getting that error, but I have not code which requires use of an <identifier>. I've been staring at this screen for like 3 hours now and I cant figure it out...Any help is greatly appreciated
    public class ConTest
            Scanner scan = new Scanner(System.in);
            char c = 'z';
            String choice;
            String temp;
            System.out.println("Choose one of the following operations:");
            System.out.println("    - Infix to postfix conversion (enter the letter i)");
            System.out.println("    - Postfix expression evaluation (enter the letter p)");
            System.out.println("    - Arithmetic expression evaluation (enter the letter a)");
            System.out.println("    - Quit (enter the letter q)");
            while(c != 'q' && c != 'Q'){
                System.out.println("Which operation do you want? ");
                choice = scan.nextLine();
                c = choice.charAt(0);
                switch(c)
                    case 'A':
                    case 'a':
                        System.out.println("Input your infix expression:\n");
                        temp = Converter.infixToPostfix(scan.nextLine());
                        System.out.println("The value of the arithmetic expression is " +
                            Converter.postfixValue(temp) + "\n");
                        break;
                    case 'I':
                    case 'i':
                        System.out.println("Input your infix expression:\n");
                        System.out.println("The postfix expression is " + Converter.infixToPostfix(scan.nextLine())
                            + "\n");
                        break;
                    case 'P':
                    case 'p':
                        System.out.println("Input your postfix expression:\n");
                        System.out.println("The value of the postfix expression is " +
                            Converter.postfixValue(scan.nextLine()) + "\n");
                        break;
                    case 'Q':
                    case 'q':
                        System.out.println("quitting\n");
                        break;
                    default:
                        System.out.println("Invalid choice\n");
    }It's just some code to test my infixToPostfix and postfixValue static methods of a separate class.

    System.out.println("Choose one of the following operations:");How do you expect this line of code (and the ones following it) to be executed? They are not inside any valid place. They need to be in a method, constructor, or initializer block (and maybe I left out a couple of other terms, but the point is you have these lines of code in an illegal place.

  • Help with CastException please

    Hi,
    i am working on program that converts a string from infix notation to postfix notation and then evaluates it. I am having a problem with the evaluation part.
    lets say we have 2 + 4 - 3
    the postfix will be 2 4 + 3 -
    The program does 2 + 4 and pushes the result onto the stack. When it gets to the - and tries to do 6 - 3, that is where the problem is. WHen i pushed the first result back onto the stack i am pusing an Integer Object. When i am popping, i am converting it to an int by parsing it. I think this is where the error is, but i am not sure.
    here is my code below. Its very long, but the part where the error is happening is in the evaluate method.
    import java.io.*;
    import javax.swing.*;
    import java.util.*;
    class InfixToPostfix
         private Stack theStack;
         private String postfix;
         public InfixToPostfix()
              postfix=" ";
         public String toPostFix(String exp)
              StringTokenizer tokLine = new StringTokenizer(exp);
              theStack = new Stack(tokLine.countTokens());
              while (tokLine.hasMoreTokens())
                   String token = (String)tokLine.nextToken();
                   if(postfix.charAt(0)!='S')
                        if(token.equals("+") || token.equals("-"))
                             gotOperator(token, 1);
                        else if(token.equals("/") || token.equals("*") || token.equals("%"))
                             gotOperator(token, 2);
                        else if(token.equals("(")==true)
                             theStack.push(token);
                        else if(token.equals(")")==true)
                             gotParen();
                        else                    
                             postfix = postfix + token + " ";
              while (!theStack.isEmpty())
                   if(postfix.charAt(0)!='S')
                        postfix = postfix + theStack.pop() + " ";
              return postfix; // return postfix
         public void gotOperator(String op, int prec)
              if(theStack.isEmpty()==false)
                   String opTop = (String)theStack.peek();
                   int precTop;
                   if(opTop.equals("+") || opTop.equals("-"))
                        precTop = 1;
                   else
                        precTop = 2;
                   if(opTop.equals("("))
                        theStack.push(op);
                   else
                        if(prec > precTop)
                             theStack.push(op);
                        if(prec <= precTop)
                             opTop = (String)theStack.pop();
                             postfix = postfix + opTop + " ";
                             theStack.push(op);
              else
                   theStack.push(op);
         public void gotParen()
              if(theStack.isEmpty()!=true)
                   String opTop = (String)theStack.peek();
                   while(opTop.equals("(")!=true && theStack.isEmpty()!=true)
                        opTop = (String)theStack.pop();
                        postfix = postfix + opTop + " ";
                        opTop = (String)theStack.peek();
                   if(opTop.equals("("));
                        opTop = (String)theStack.pop();
              else
                   postfix = "Sytanx Error. Extra right parenthesis";     
         public Object evaluate(String postfix)
              StringTokenizer tokLine = new StringTokenizer(postfix);
              Stack evalStack = new Stack(tokLine.countTokens());
              int value = 0;
              int operand2, operand1;
              String item,result=" ";
              while(tokLine.hasMoreTokens())
                   item = (String)tokLine.nextToken();
                   if(item.equals("+"))
                        if(evalStack.isEmpty()!=true)
                             operand2 = Integer.parseInt((String)evalStack.pop());
                             if(evalStack.isEmpty()!=true)
                                  operand1 = Integer.parseInt((String)evalStack.pop());
                                  value = operand1 + operand2;
                                  Integer pushValue = new Integer(value);
                                  evalStack.push(pushValue);
                             else
                                  result = "Error: Not enough operands.";
                        else
                             result = "Error: Not enough operands.";
                   else if(item.equals("-"))
                        if(evalStack.isEmpty()!=true)
                             operand2 = Integer.parseInt((String)evalStack.pop());
                             if(evalStack.isEmpty()!=true)
                                  operand1 = Integer.parseInt((String)evalStack.pop());
                                  value = operand1 - operand2;
                                  Integer pushValue = new Integer(value);
                                  evalStack.push(pushValue);
                             else
                                  result = "Error: not enough operands.";
                        else
                             result = "Error: not enough operands.";
                   else if(item.equals("*"))
                        if(evalStack.isEmpty()!=true)
                             operand2 = Integer.parseInt((String)evalStack.pop());
                             if(evalStack.isEmpty()!=true)
                                  operand1 = Integer.parseInt((String)evalStack.pop());
                                  value = operand1 * operand2;
                                  Integer pushValue = new Integer(value);
                                  evalStack.push(pushValue);
                             else
                                  result = "Error: not enough operands.";
                        result = "Error: not enough operands.";
                   else if(item.equals("/"))
                        if(evalStack.isEmpty()!=true)
                             operand2 = Integer.parseInt((String)evalStack.pop());
                             if(evalStack.isEmpty()!=true)
                                  operand1 = Integer.parseInt((String)evalStack.pop());
                                  value = operand1 / operand2;
                                  Integer pushValue = new Integer(value);
                                  evalStack.push(pushValue);
                             else
                                  result = "Error: not enough operands.";
                        else
                             result = "Error: not enough operands.";
                   else if(item.equals("%"))
                        if(evalStack.isEmpty()!=true)
                             operand2 = Integer.parseInt((String)evalStack.pop());
                             if(evalStack.isEmpty()!=true)
                                  operand1 = Integer.parseInt((String)evalStack.pop());
                                  value = operand1 % operand2;
                                  Integer pushValue = new Integer(value);
                                  evalStack.push(pushValue);
                             else
                                  result = "Error: not enough operands.";
                        else
                             result = "Error: not enough operands.";          
                   else
                        evalStack.push(item);
              Object finalValue = new Object();
              finalValue = evalStack.pop();
              if(evalStack.isEmpty()!=true)
                   result = "Error: Not enough operators.";
              if(result.equals(" "))
                   return  finalValue;
              return (Object)result;
    }can you tell me what i need to do to fix the Cast Exception that i am getting?
    this is the error that it is giving.
    java.lang.ClassCastException
         at InfixToPostfix.evaluate(InfixToPostfix.java:117)

    I added a small main() method to test your code:
        public static void main(String[] args) throws Exception {
            InfixToPostfix x = new InfixToPostfix();
            System.out.println(x.evaluate("4 2 3 + -"));
        }and got this:
    Exception in thread "main" java.lang.ClassCastException: java.lang.Integer
            at InfixToPostfix.evaluate(InfixToPostfix.java:134)
            at InfixToPostfix.main(InfixToPostfix.java:12)The problem is that you have put a java.lang.Integer object on the stack, but in line 134 (or line 117 in your version of the code) you are getting an object off the stack and you cast it to a String.
    You can't cast an Integer to a String.

  • My infix to postfix algorithm

    I need som help to finish my algorithm.
    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...
    And it's only supposed to handle one digits numbers.
    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>

    Code tags, please: http://forum.java.sun.com/help.jspa?sec=formatting

  • 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 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

  • Convertion algorithm - notations

    I need som help to finish my algorithm.
    I wanna convert a string from infix to postfix.
    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...
    And it's only supposed to handle one digits numbers.
    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 mikky
    I guess cepstrum vi will be in the next version of "advanced signal processing toolset". Now, it is a beta version. Pwehaps you can ask your local NI representative to get a copy for you.
    Cheers
    Alipio
    "Qod natura non dat, Salmantica non praestat"

  • Compare operator

    I am trying to compare two operators.
    The operators are: + - * / ^
    They have all different priority
    ^ = 3
    * = 2
    / = 2
    + = 1
    - = 1
    How can I compare a character '*' with
    a character '+' of which one has the
    highest priority?

    I thought this really would work, but
    surely I have missed something.
    This is my code:
    import java.util.*;
    import javax.swing.*;
    public class InfixToPostfix {
         public static void main(String[] args) {
              Object slutt            = "#";
              String infixStr      = JOptionPane.showInputDialog("Tast inn infix-uttrykket: ");
              infixStr              += slutt;
              String postfixStr     = "";
              System.out.println("Infix: "+infixStr);
              Stack stack = new Stack();
              stack.add(slutt);
              System.out.println ("Stack is empty: "+stack.empty ()+ ", Stack: " + stack);
              Map <String, Integer> priorities = new HashMap<String, Integer>();
              priorities.put("^", 3);
              priorities.put("*", 2);
              priorities.put("*", 2);
              priorities.put("+", 1);
              priorities.put("-", 1);
              priorities.put("#", 0);
              //String op = "+";
              Object c;
              String stackOp;
              String infixOp;
              int infixPri;
              int stackPri;
              for (int i=0; i<infixStr.length(); i++) {
                   c = infixStr.charAt(i);
                   infixOp= c.toString();
                   infixPri = priorities.get(infixOp);
                   System.out.println("A: "+infixPri+infixOp);
                   if (infixOp == "+" || infixOp == "-" || infixOp == "*" || infixOp == "/" || infixOp == "^") {
                        if (stack.empty()) {
                             stack.push(String.valueOf(c));
                        else {
                             while (!stack.empty()) {
                                  stackOp = (String) stack.pop();
                                  stackPri = priorities.get(stackOp);
                                  if (stackPri >= infixPri) {
                                       postfixStr += stackOp;
                                  else stack.push(String.valueOf(c));
                   else if (c == "#") {
                        System.out.println("Postfix: "+ postfixStr);
                        System.exit(0);
                   else {
                        postfixStr += c;
    }At these lines: "stack.push(String.valueOf(c));"
    I get this message -->
    Type safety: The method push(Object) belongs to the raw type Stack. References to generic type
    Stack<E> should be parameterized

  • Stack and queue problem

    hi i am trying to change infix expression to postfix and also the opposite, like
    ((a+b)*(a-c*d)/(b+d*e)) to ab+acb*-bde+/
    using stack and queue
    I am so confuse

    Hello,
    See this URL :
    http://www24.brinkster.com/premshree/perl
    You will find the algorithms here.
    Here is a Perl version :
    #     Script:          infix-postfix.pl
    #     Author:          Premshree Pillai
    #     Description:     Using this script you can :
    #               - Convert an Infix expression to Postfix
    #               - Convert a Postfix expression to Infix
    #               - Evaluate a Postfix expression
    #               - Evaluate an Infix expression
    #     Web:          http://www.qiksearch.com
    #     Created:     23/09/02 (dd/mm/yy)
    #     � 2002 Premshree Pillai. All rights reserved.
    sub isOperand
         ($who)=@_;
         if((!isOperator($who)) && ($who ne "(") && ($who ne ")"))
              return 1;
         else
              return;
    sub isOperator
         ($who)=@_;
         if(($who eq "+") || ($who eq "-") || ($who eq "*") || ($who eq "/") || ($who eq "^"))
              return 1;
         else
              return;
    sub topStack
         (@arr)=@_;
         my $arr_len=@arr;
         return($arr[$arr_len-1]);
    sub isEmpty
         (@arr)=@_;
         my $arr_len=@arr;
         if(($arr_len)==0)
              return 1;
         else
              return;
    sub prcd
         ($who)=@_;
         my $retVal;
         if($who eq "^")
              $retVal="5";
         elsif(($who eq "*") || ($who eq "/"))
              $retVal="4";
         elsif(($who eq "+") || ($who eq "-"))
              $retVal="3";
         elsif($who eq "(")
              $retVal="2";
         else
              $retVal="1";
         return($retVal);
    sub genArr
         ($who)=@_;
         my @whoArr;
         for($i=0; $i<length($who); $i++)
              $whoArr[$i]=substr($who,$i,1);
         return(@whoArr);
    sub InfixToPostfix
         ($infixStr)=@_;
         my @infixArr=genArr($infixStr);
         my @postfixArr;
         my @stackArr;
         my $postfixPtr=0;
         for($i=0; $i<length($infixStr); $i++)
              if(isOperand($infixArr[$i]))
                   $postfixArr[$postfixPtr]=$infixArr[$i];
                   $postfixPtr++;
              if(isOperator($infixArr[$i]))
                   if($infixArr[$i] ne "^")
                        while((!isEmpty(@stackArr)) && (prcd($infixArr[$i])<=prcd(topStack(@stackArr))))
                             $postfixArr[$postfixPtr]=topStack(@stackArr);
                             pop(@stackArr);
                             $postfixPtr++;
                   else
                        while((!isEmpty(@stackArr)) && (prcd($infixArr[$i])<prcd(topStack(@stackArr))))
                             $postfixArr[$postfixPtr]=topStack(@stackArr);
                             pop(@stackArr);
                             $postfixPtr++;
                   push(@stackArr,$infixArr[$i]);
              if($infixArr[$i] eq "(")
                   push(@stackArr,$infixArr[$i])
              if($infixArr[$i] eq ")")
                   while(topStack(@stackArr) ne "(")
                        $postfixArr[$postfixPtr]=pop(@stackArr);
                        $postfixPtr++;
                   pop(@stackArr);
         while(!isEmpty(@stackArr))
              if(topStack(@stackArr) eq "(")
                   pop(@stackArr)
              else
                   $temp=@postfixArr;
                   $postfixArr[$temp]=pop(@stackArr);
         return(@postfixArr);
    sub PostfixToInfix
         ($postfixStr)=@_;
         my @stackArr;
         my @postfixArr=genArr($postfixStr);
         for($i=0; $i<length($postfixStr); $i++)
              if(isOperand($postfixArr[$i]))
                   push(@stackArr,$postfixArr[$i]);
              else
                   $temp=topStack(@stackArr);
                   pop(@stackArr);
                   $pushVal=topStack(@stackArr).$postfixArr[$i].$temp;
                   pop(@stackArr);
                   push(@stackArr,$pushVal);
         return((@stackArr));
    sub PostfixEval
         ($postfixStr)=@_;
         my @stackArr;
         my @postfixArr=genArr($postfixStr);
         for($i=0; $i<length($postfixStr); $i++)
              if(isOperand($postfixArr[$i]))
                   push(@stackArr,$postfixArr[$i]);
              else
                   $temp=topStack(@stackArr);
                   pop(@stackArr);
                   $pushVal=PostfixSubEval(topStack(@stackArr),$temp,$postfixArr[$i]);
                   pop(@stackArr);
                   push(@stackArr,$pushVal);
         return(topStack(@stackArr));
    sub PostfixSubEval
         ($num1,$num2,$sym)=@_;
         my $returnVal;
         if($sym eq "+")
              $returnVal=$num1+$num2;
         if($sym eq "-")
              $returnVal=$num1-$num2;
         if($sym eq "*")
              $returnVal=$num1*$num2;
         if($sym eq "/")
              $returnVal=$num1/$num2;
         if($sym eq "^")
              $returnVal=$num1**$num2;
         return($returnVal);
    sub joinArr
         (@who)=@_;
         my $who_len=@who;
         my $retVal;
         for($i=0; $i<$who_len; $i++)
              $retVal.=$who[$i];
         return $retVal;
    sub evalInfix
         ($exp)=@_;
         return PostfixEval(joinArr(InfixToPostfix($exp)));
    sub init
         my $def_exit="\n\tThank you for using this Program!\n\tFor more scripts visit http://www.qiksearch.com\n";
         printf "\n\tInfix - Postfix\n";
         printf "\n\tMenu";
         printf "\n\t(0) Convert an Infix Expression to Postfix Expression";
         printf "\n\t(1) Convert a Postfix Expression to Infix Expression";
         printf "\n\t(2) Evaluate a Postifx Expression";
         printf "\n\t(3) Evaluate an Infix Expression";
         printf "\n\t(4) Exit this Program";
         printf "\n\t(5) About this Program\n";
         printf "\n\tWhat do you want to do? (0/1/2/3/4/5) ";
         $get=<STDIN>;
         chomp $get;
         if(!(($get eq "0") || ($get eq "1") || ($get eq "2") || ($get eq "3") || ($get eq "4") || ($get eq "5")))
              printf "\n\t'$get' is an illegal character.\n\tYou must enter 0/1/2/3/4/5.";
         if(($get ne "4") && ($get ne "5") && (($get eq "0") || ($get eq "1") || ($get eq "2") || ($get eq "3")))
              printf "\n\tEnter String : ";
              $getStr=<STDIN>;
              chomp $getStr;
         if($get eq "0")
              printf "\tPostfix String : ";
              print InfixToPostfix($getStr);
         if($get eq "1")
              printf "\tInfix String : ";
              print PostfixToInfix($getStr);
         if($get eq "2")
              printf "\tPostfix Eval : ";
              print PostfixEval($getStr);
         if($get eq "3")
              printf "\tExpression Eval : ";
              print evalInfix($getStr);
         if($get eq "4")
              printf $def_exit;
              exit 0;
         if($get eq "5")
              printf "\n\t======================================================";
              printf "\n\t\tInfix-Postfix Script (written in Perl)";
              printf "\n\t\t(C) 2002 Premshree Pillai";
              printf "\n\t\tWeb : http://www.qiksearch.com";
              printf "\n\t======================================================\n";
              printf "\n\tUsing this program, you can : ";
              printf "\n\t- Convert an Infix Expression to Postfix Expression.";
              printf "\n\t Eg : 1+(2*3)^2 converts to 123*2^+";
              printf "\n\t- Convert a Postfix Expression to Infix Expression.";
              printf "\n\t Eg : 123*+ converts to 1+2*3";
              printf "\n\t- Evaluate a Postfix Expression";
              printf "\n\t Eg : 37+53-2^/ evaluates to 2.5";
              printf "\n\t- Evaluate an Infix Expression";
              printf "\n\t Eg : (5+(4*3-1))/4 evaluates to 4";
              printf "\n\n\tYou can find the algorithms used in this Program at : ";
              printf "\n\t-http://www.qiksearch.com/articles/cs/infix-postfix/index.htm";
              printf "\n\t-http://www.qiksearch.com/articles/cs/postfix-evaluation/index.htm";
              printf "\n\n\tYou can find a JavaScript implementation of 'Infix-Postfix' at : ";
              printf "\n\t-http://www.qiksearch.com/javascripts/infix-postfix.htm";
         printf "\n\n\tDo you want to continue? (y/n) ";
         my $cont=<STDIN>;
         chomp $cont;
         if($cont eq "y")
              init();
         else
              printf $def_exit;
              exit 0;
    init;

Maybe you are looking for