che*_*ish 1 java postfix-notation
我为后缀求值器编程,并且我能够正确地为个位数编号。现在我需要了解如何处理多位数,因为我当前的程序将两位数评估为不同的数字。
这是代码:
public class PostfixEvaluation {
public static void main(String[] args) {
String postfix = "23+79*-";
Stack stack = new Stack();
for (int i = 0; i < postfix.length(); i++) {
if (postfix.charAt(i) == '+') {
int v1 = stack.pop();
int v2 = stack.pop();
stack.push(v2 + v1);
} else if (postfix.charAt(i) == '-') {
int v1 = stack.pop();
int v2 = stack.pop();
stack.push(v2 - v1);
} else if (postfix.charAt(i) == '*') {
int v1 = stack.pop();
int v2 = stack.pop();
stack.push(v2 * v1);
} else if (postfix.charAt(i) == '/') {
int v1 = stack.pop();
int v2 = stack.pop();
stack.push(v2 / v1);
} else if (postfix.charAt(i) == '^') {
int v1 = stack.pop();
int v2 = stack.pop();
stack.push((int) Math.pow(v2, v1));
} else {
stack.push((int) postfix.charAt(i) - 48);
}
}
System.out.println(stack.pop());
}
}
Run Code Online (Sandbox Code Playgroud)
为了能够识别多位数字,两个数字之间必须有一个分隔符。
例如,您可以使用空格作为分隔符。中的所有标记都postfix将被空格分隔。你的例子会变成"2 3 + 7 9 * -". 您应该一次读取一个标记,而不是一个字符。