Postfix Calculator Java

Jmamz06 picture Jmamz06 · Sep 4, 2012 · Viewed 33.2k times · Source

Ok so I have to read in a postfix expression from a file. The postfix expression must have spaces to separate each operator or operand. What I have so far works only if there is no spaces between the operators or operands in the input file. (i.e. if the file has 12+ the result I get is 3.) In order to do this I think that I need to tokenize the input, but I am not sure how. This is what I have so far. Thank you for any responses.

import java.util.*;
import java.io.*;
public class PostfixCalc{
public static void main (String [] args) throws Exception {
File file = new File("in.txt");
Scanner sc = new Scanner(file);
String input = sc.next();
Stack<Integer> calc = new Stack<Integer>();
while(sc.hasNext()){
for(int i = 0; i < input.length(); i++){
    char c = input.charAt(i);
    int x = 0;
    int y = 0;
    int r = 0;
    if(Character.isDigit(c)){
       int t = Character.getNumericValue(c);
        calc.push(t);
    }
    else if(c == '+'){
        x = calc.pop();
        y = calc.pop();
        r = x+y;
        calc.push(r);
    }
     else if(c == '-'){
        x = calc.pop();
        y = calc.pop();
        r = x-y;
        calc.push(r);
    }
     else if(c == '*'){
        x = calc.pop();
        y = calc.pop();
        r = x*y;
        calc.push(r);
    }
     else if(c == '/'){
        x = calc.pop();
        y = calc.pop();
        r = x/y;
        calc.push(r);
    }
}
 }
 int a = calc.pop();
System.out.println(a);
 }
 } 

Answer

biziclop picture biziclop · Sep 4, 2012

There are several things you need to change, which you can do step by step.

  1. Declare your Stack to contain Integers rather than Characters.
  2. In the code that reads the input, rely on Strings instead of Characters.
  3. Parse operands using Integer.parseInt(). This will convert Strings to Integers. (Actually, it converts them to ints, but in your case this difference doesn't matter.)
  4. Set the scanner delimiter using Scanner.useDelimiter() to \s+, this will match a sequence of any whitespace characters.

There are of course countless of other ways to process your input but I tried to give you an idea of how to change your existing code to do what it needs to do.