【发布时间】:2012-08-29 10:48:02
【问题描述】:
好的,所以我必须从文件中读取后缀表达式。后缀表达式必须有空格来分隔每个运算符或操作数。到目前为止,我只有在输入文件中的运算符或操作数之间没有空格时才有效。 (即如果文件有 12+,我得到的结果是 3。)为了做到这一点,我认为我需要对输入进行标记,但我不确定如何。这就是我到目前为止所拥有的。感谢您的任何回复。
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);
}
}
【问题讨论】:
-
看看
StringTokenizer。默认情况下,它会标记空白(空格、制表符、换行符等)。
标签: java calculator postfix-notation stack