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);
}
}
There are several things you need to change, which you can do step by step.
Stack
to contain Integer
s rather than Character
s.String
s instead of Character
s.Integer.parseInt()
. This will convert String
s to Integer
s. (Actually, it converts them to int
s, but in your case this difference doesn't matter.)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.