在这个输入问题中,有一个以后缀表示法给出的语句,我的任务是评估给定的语句。我完全理解该算法,我将在下面发布我的解决方案。但由于某种原因,它适用于这些: 1 2 3 * + 5 -、1 1 1 - - 1 + 1 +、1 2 + ... 等,但当存在像这样的多位数数字时,它不起作用一:100 20-。我的解决方案(java):
public class PostFixEvaluation {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String expression = br.readLine();
char exp[] = expression.toCharArray();
ArrayStack<Integer> op = new ArrayStack<Integer>(100);
int vrednost = 0;
int dolzina = 0;
int suma = 0;
int res=0;
int convert = 0;
char ch;
for(int i=0; i < exp.length; i++){
ch = exp[i];
if(Character.isDigit(ch)){
convert = (int)ch-'0';
op.push(convert);
convert = 0;
}
else if(exp[i] == '+'){
int x = op.pop();
int y = op.pop();
vrednost = x + y;
op.push(vrednost);
vrednost = 0;
}
else if(exp[i] == '-'){
int x = op.pop();
int y = op.pop();
vrednost = y - x;
op.push(vrednost);
vrednost = 0;
}
else if(exp[i] == '*'){
int x = op.pop();
int y = op.pop();
vrednost = y * x;
op.push(vrednost);
vrednost = 0;
}
else if(exp[i] == '/'){
int x = op.pop();
int y = op.pop();
vrednost = y/x;
op.push(vrednost);
vrednost = 0;
}
}
res = op.pop();
System.out.println(res);
br.close();
}
}
最佳答案
你在这里做什么...
for(int i=0; i < exp.length; i++){
ch = exp[i];
if(Character.isDigit(ch)){
convert = (int)ch-'0';
op.push(convert);
convert = 0;
}
...正在读取单个字符,并将其插入数字堆栈中。问题是您没有检查该字符是否只是数字的第一个数字。
如果你的代码遇到"100 20 -"
,则会推送"1"
, "0"
, "0 "
、"2"
、"0"
放入您的数字堆栈,而不是 "100"
、"20 “
。
您需要重写解析代码以获取整个数字,而不是单独检查每个字符。
更新
关于更好的解析方法,Java 有一些非常好的内置 String
解析工具。
在这种情况下,我建议使用 Scanner
解析表达式
而不是将其转换为char[]
。您可以使用 hasNext()
和 hasNextInt()
等方法来检查是否有更多输入,以及该输入是否为 int
,以及next()
和 nextInt()
读取下一个标记。
例如
Scanner scanner = new Scanner(expression);
while (scanner.hasNext()) { // while there more input...
if (scanner.hasNextInt()) { // is the next token an int?
int number = scanner.nextInt(); // read the next token as an integer
op.push(number);
} else { // the next token is NOT an int
String operator = scanner.next(); // read the next token as a String
if (operator.equals("+")) {
// same as before
} else if (operator.equals("-")) {
// same as before
} else if (operator.equals("*")) {
// same as before
} else if (operator.equals("/")) {
// same as before
}
}
}
关于java - Postfix 评估(小错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26661559/