Question

The code posted works for operations but wont work if there isnt spacing between the operators and operands.

I was given 4 expressions to compute

  1. 10 2 8 * + 3 -

  2. 3 14+2*7/

  3. 4 2 + 3 15 1 - * +

  4. 1 2 + 3 % 6 - 2 3 + /

(spacing is important)

Expression two is the one that will not compute using my current calculator

Here is my code

  import java.util.*;
  public class PostFix {

   public static void main(String []args){

    Stack<Integer> stack = new Stack<Integer>();
    System.out.println("Input your expression using postfix notation");
    Scanner input = new Scanner(System.in);
        String expr = input.nextLine();
        StringTokenizer tokenizer = new StringTokenizer(expr);

    while(tokenizer.hasMoreTokens()){
        String c = tokenizer.nextToken();
        if(c.startsWith("0")|| c.startsWith("1")||c.startsWith("2")||c.startsWith("3")||c.startsWith("4")||
            c.startsWith("5")||c.startsWith("6")||c.startsWith("7")||c.startsWith("8")||c.startsWith("9"))
            stack.push(Integer.parseInt(c));
        else if(c.equals("+")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2+op1);
        }
        else if(c.equals("-")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2-op1);
        }
        else if(c.equals("*")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2*op1);
        }
        else if(c.equals("/")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2/op1);
        }
        else if(c.equals("%")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op1%op2);
        }



    }
System.out.println(stack.pop());

}
   }

Here is the StackTrace

 Input your expression using postfix notation
 3 14+2*7/
 Exception in thread "main" java.lang.NumberFormatException: For input string:  "14+2*7/"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at PostFix.main(PostFix.java:18)
Was it helpful?

Solution

If you really have to use StringTokenizer, construct it like this:

StringTokenizer tokenizer = new StringTokenizer(expr, " +-*/%", true);

The second parameter says that spaces and all the operators are considered delimiters, in addition to spaces. The third parameter says that the delimiters are treated as tokens, so when it sees "+", "-", etc., it will return that as a string. It will also return spaces, so you have to make sure that when nextToken returns " ", you ignore it and don't treat it as an error.

OTHER TIPS

Alternatively, if you can't use StreamTokenizer, use the 3-argument version of the StringTokenizer constructor:

StringTokenizer tokenizer = new StringTokenizer(expr, " +*-/", true);

This will make ' ', '+', '*', '-' and '/' delimiters and also report them as tokens.

Use a StreamTokenizer for parsing, see http://docs.oracle.com/javase/7/docs/api/java/io/StreamTokenizer.html

StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expr));
tokenizer.ordinaryChar('/');  // see comments

while(tokenizer.nextToken() != StreamTokenizer.TT_EOF){
  if (tonenizer.ttype == StreamTokenizer.TT_NUMBER) {
    stack.push(Integer.parseInt(tokenizer.sval));
  } else {
    int op1 = stack.pop();
    int op2 = stack.pop();
    switch (ttype) {
      case '+': op2 += op1; break;
      case '-': op2 -= op1; break;
      case '*': op2 *= op1; break;
      case '/': op2 /= op1; break;
    }
    stack.push(op2);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top