Results 1 to 19 of 19
  1. #1
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default problem with infix post fix evaluate

    hey guys i got this code but sometimes it makes wrong evaluation and i don t know why.any thought?
    Java Code:
    public class Calculator {
    
           static int precedence(char op) {
                  switch(op) {
                  case '+' :
                  case '-' : 
                           return 5;
                  case '*' :
                  case '/' :
                           return 10;
                  default :
                           throw new IllegalArgumentException("invalid operator");
                   }
             }
           public static String infixToPostfix(String infix) {
                  StringTokenizer tokenizer = new StringTokenizer (infix);
                  String postfix = "";
                  Stack opStack = new Stack ();
    
                  while (tokenizer.hasMoreTokens()) {
                         String token = tokenizer.nextToken();
                         char c = token.charAt(0);
                         if (Character.isDigit(c)){
                                postfix +=(token + " ");
                         }
                         else {
                                 while (!opStack.empty()){
                                        char top = ((Character)opStack.peek()).charValue();
                                        if (precedence(top) >= precedence(c)) {
                                                postfix += (top + " ");
                                                opStack.pop();
                                         }
                                         else {
                                                break;
                                               }
                                         }
                                         opStack.push(new Character (c));
                              }
                          }
                 
                   while (!opStack.empty()) {
                          char top = ((Character)opStack.pop()).charValue();
                          postfix += (top + " ");
                    }
                    return postfix;
            }
    
         public static int evalPostfix(String postfix) {
                  StringTokenizer tokenizer = new StringTokenizer(postfix);
                  Stack valStack = new Stack();
    
                  while(tokenizer.hasMoreTokens()) {
                         String token = tokenizer.nextToken();
                         char c = token.charAt(0);
                         if (Character.isDigit(c)) {
                                valStack.push(new Integer(token));
                          }
                          else {
                                  int rightVal = ((Integer)valStack.pop()).intValue();
                                  int leftVal = ((Integer)valStack.pop()).intValue();
                                  int rslt;
    
                                  switch(c) {
                                  case '+' : rslt = leftVal + rightVal;break;
                                  case '-' : rslt = leftVal - rightVal;break;
                                  case '*' : rslt = leftVal * rightVal;break;
                                  case '/' : rslt = leftVal + rightVal;break;
                                  default:
                                         throw new IllegalArgumentException("invalid postfix expression");
                                    }
                                   valStack.push(new Integer(rslt));
                                }
                         }
                     int rslt = ((Integer)valStack.pop()).intValue();
                     if (!valStack.empty()){
                              throw new IllegalArgumentException("invalid postfix expression");
                      }
                          return rslt;
              }
          public static void main(String[] args)  {
                 String infix = args[0];
                 String postfix = infixToPostfix(infix); 
                 System.out.println("postfix"+postfix);
                 int value = evalPostfix(postfix);
                 System.out.println("value: " + value);
             }
    }
    can anyone run it and see if it evaluates right to you?i ask because i do it on an online compiler and maybe that affects it

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: problem with infix post fix evaluate

    Before I delve into this, have you checked you postfix expression to ensure it is in postfix notation before processing? I assume you are converting regular algebraic expressions to postfix.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    yeah i think everything is alright.sorry if i have mistakes.i m newb to java and i got this as an assignment and i have to give it in 4 days :/
    yeah its a program where the user inputs an algebraic infix something like 10*8+5 etc it makes it postfix and evaluates

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: problem with infix post fix evaluate

    Maybe you'll find one of my blog articles of interest (see the top right corner of this reply for a link to my blogs); it discusses an expression parser and implements (among other things) what you're working on.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    anyone tried my program to see if it works?and where is the problem?i m struggling over here :/

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: problem with infix post fix evaluate

    Quote Originally Posted by alexd View Post
    can anyone run it and see if it evaluates right to you?i ask because i do it on an online compiler and maybe that affects it
    Sorry but that is something you can easily test yourself.

    I'm not going to debug your code for you, if you don't manage to do it yourself that is too bad, you're not going to succeed in this assignment. Failure is not the end of the world, it often leads to good things. And even if your program contains a little bug somewhere that you can't find, the effort you did to create it should already net you plenty of credit.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    Quote Originally Posted by gimbal2 View Post
    Sorry but that is something you can easily test yourself.

    I'm not going to debug your code for you, if you don't manage to do it yourself that is too bad, you're not going to succeed in this assignment. Failure is not the end of the world, it often leads to good things. And even if your program contains a little bug somewhere that you can't find, the effort you did to create it should already net you plenty of credit.
    you don t understand.the program runs.i just need some help in order to see why sometimes it posts the wrong result.afterall this is the forum for people new at java asking for some assistance.i didn t ask anyone to write all the program for me.i just asked for some help.wtf logic is that?then delete the forum since everyone is on his own and if they don t succeed then that s ok i guess?

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: problem with infix post fix evaluate

    Have you tried to print out the postfix string before you try to evaluate it? Is the string correct for every infix expression you supply?

    kind regards,

    Jos

    edit: the infix to postfix stuff seems to be correct as well as the postfix string evaluation; getting the infix string from args[0] in your main method is a nono.
    Last edited by JosAH; 02-07-2014 at 03:43 PM.
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    Quote Originally Posted by JosAH View Post
    Have you tried to print out the postfix string before you try to evaluate it? Is the string correct for every infix expression you supply?

    kind regards,

    Jos

    edit: the infix to postfix stuff seems to be correct as well as the postfix string evaluation; getting the infix string from args[0] in your main method is a nono.
    why is it wrong to take it from the args?how should i have taken it instead?

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: problem with infix post fix evaluate

    Quote Originally Posted by alexd View Post
    why is it wrong to take it from the args?how should i have taken it instead?
    space characters? Arguments (on the command line) need to be separated by spaces while the tokenizer also needs spaces to separate tokens ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: problem with infix post fix evaluate

    One reason I can think of is that for this type of application, it imposes an unfair requirement on the user. To enclose the expression in quotation marks or forbid white space altogether. Otherwise, embedded spaces will populate more than just args[0].

    Edit: Stuck in my editor for 10 minutes, trying to respond to the right person and Jos already says it. I really don't like this thread manager.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  12. #12
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    Quote Originally Posted by JosAH View Post
    space characters? Arguments (on the command line) need to be separated by spaces while the tokenizer also needs spaces to separate tokens ...

    kind regards,

    Jos
    thank you for trying to help me but i still don t quite undestand.so what should i change and in what line in order for this to work?
    it post me at line 84(the line you said as nono )
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Calculator.main(Calculator.java:84)
    what should i do then?

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: problem with infix post fix evaluate

    Check out the Scanner class. Specifically, the nextLine method.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  14. #14
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    ok so i wrote in in other way and now it runs.the only problem is that sometimes it makes wrong evaluation.why?here is the code
    Java Code:
     import java.io.*; 
    import java.util.*;
    
    public class Expressions 
    { 
         public static void main (String [] args) 
         { 
            System.out.println ("Enter an infix expression:"); 
            Token token = new Token (); 
            token.getToken (); 
            Express express = new Express (token); 
            int result = express.expression (); 
            System.out.println ("= " + result); 
         } // main method 
    } // class Expressions
    
    class Token 
    { 
         private int value = 0; 
         private String name, tokenString; 
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); 
        StringTokenizer tokens;
    
        Token () 
        { 
             try 
             { 
                  tokenString = stdin.readLine (); 
                  tokens = new StringTokenizer (tokenString, "+-*/() ", true); 
             } catch (IOException e) {System.out.println ("Input error");} 
        } // constructor 
      
         public void getToken () 
         { 
              char ch = ' '; 
              if (tokens.hasMoreTokens ()) 
              { 
                   String token = tokens.nextToken (); 
                   ch = token.charAt (0); 
                   while (ch == ' ') 
                   { 
                        token = tokens.nextToken (); 
                        ch = token.charAt (0); 
                   } 
                   if (('0' <= ch) && (ch <= '9')) 
                   { 
                        name = "digit"; 
                        try 
                        { value = Integer.parseInt (token); 
                        } catch (NumberFormatException e) {value = 0;} 
                   } 
                   else 
                   {    switch (ch) 
                        { 
                             case '+': name = "plus"; break; 
                             case '-': name = "minus"; break; 
                             case '*': name = "times"; break; 
                             case '/': name = "divide"; break; 
                             case '(': name = "lparen"; break; 
                             case ')': name = "rparen"; break; 
                             default: name = "other"; 
                        } //switch 
                   } // else 
              } 
              else name = "other"; 
         } //method getToken 
      
         public String getName () { return name; } 
         public int getValue () { return value; }
    
    } // class Token
    
    class Express 
    { 
         private Token token; 
      
         Express (Token token) { this.token = token; } // constructor 
      
         public int expression () 
         { 
              String oper; 
              int result; 
              result = term (); 
              while ((token.getName ().equals ("plus")) || (token.getName ().equals ("minus"))) 
              { 
               oper = token.getName (); 
                   token.getToken (); 
                   if (oper.equals ("plus")) 
                   { 
                        result = result + term (); 
                        System.out.print ("+ "); 
                    } 
                   else 
                   { 
                        result = result - term (); 
                        System.out.print ("- "); 
                   } 
              } 
              return result; 
         } // method expression 
      
         public int term () 
         { 
              String oper; 
              int result; 
              result = factor (); 
              while ((token.getName ().equals ("times")) || (token.getName ().equals ("divide"))) 
              { 
                   oper = token.getName (); 
                   token.getToken (); 
                   if (oper.equals ("times")) 
                   { 
                        result = result * factor (); 
                        System.out.print ("* "); 
                   } 
                   else 
                   { 
                        result = result / factor (); 
                        System.out.print ("/ "); 
                   } 
              } 
              return result; 
         } // method term
    
         public int factor () 
         { 
              int result = 0; 
              if (token.getName ().equals ("digit")) 
              { 
                   result = token.getValue (); 
                   System.out.print ("" + token.getValue () + " "); 
                   token.getToken (); 
              } 
              else 
              if (token.getName ().equals ("lparen")) 
              { 
                   token.getToken (); 
                   result = expression (); 
                   if (token.getName ().equals ("rparen")) 
                        token.getToken (); 
                   else 
                        System.out.print ("Error - missing right paren"); 
              } 
              else 
                   System.out.print ("Error - invalid token"); 
              return result; 
         } // method factor 
    } // class

  15. #15
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: problem with infix post fix evaluate

    You should include the test expression which it is evaluating incorrectly as well as the generated output.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: problem with infix post fix evaluate

    Either change line #81 to something similar to this:

    Java Code:
    String infix= "2 + 3 * 4";
    ... or pass you String on the command line between double quotes:

    Java Code:
    java YourClass "2 + 3 * 4"
    ... or make your program read the String from System.in (or from somewhere else), but that takes a bit of additional code.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: problem with infix post fix evaluate

    I noticed you do not handle valid unary syntax. The following results in an error.

    2 * -2 + 8

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: problem with infix post fix evaluate

    Quote Originally Posted by jim829 View Post
    I noticed you do not handle valid unary syntax. The following results in an error.

    2 * -2 + 8
    It can't handle parentheses either; that's why I pointed to my blog article for a more complete implementation.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    alexd is offline Member
    Join Date
    Feb 2014
    Posts
    9
    Rep Power
    0

    Default Re: problem with infix post fix evaluate

    thank you all very much for your pointers.i got to go to work now,but when i ll come back i get right back into it.thank you

Similar Threads

  1. Problem with infix evaluator?
    By chris1 in forum New To Java
    Replies: 3
    Last Post: 10-12-2011, 02:33 AM
  2. Fence Post problem
    By seanfmglobal in forum New To Java
    Replies: 6
    Last Post: 01-20-2011, 03:53 AM
  3. Evaluate a string expression
    By aparna_pall in forum New To Java
    Replies: 2
    Last Post: 04-10-2010, 03:53 AM
  4. Infix to Post fix
    By Tenn in forum New To Java
    Replies: 0
    Last Post: 05-03-2009, 09:21 PM
  5. Replies: 1
    Last Post: 07-05-2008, 03:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •