Postfix Calculator Java

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);

Leave a Comment