我必须使用堆栈评估前缀表达式,我这样做了,但我不明白为什么代码无法正常工作,它在编译代码时标记了2个错误,它们是:使用堆栈评估前缀表达式
异常在线程 “主要” java.lang.ClassCastException:java.lang.String中不能在evaluationprefix.EvaluationPreFix.EvaluationPrefix(EvaluationPreFix.java:56) 被强制转换为java.lang.Integer中 在evaluationprefix.EvaluationPreFix。 main(EvaluationPreFix.java:25)
public class EvaluationPreFix {
public static void main(String[] args) {
Stack st = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("enter the size of expression");
int t = sc.nextInt();
sc.nextLine();
for (int i = 0; i < t; i++) {
System.out.println("enter an element");
String element = sc.nextLine();
st.push(element);
}
int r = EvaluationPrefix(st); //marks an Error here
System.out.println("Result: " + r);
}
public static int EvaluationPrefix(Stack st) {
Stack st2 = new Stack();
while (!st.isEmpty()) {
Object e = st.pop();
if (e.equals('+')) {
st2.push((Integer) st2.pop() + (Integer) st2.pop());
} else if (e.equals('-')) {
st2.push((Integer) st2.pop() - (Integer) st2.pop());
} else if (e.equals('*')) {
st2.push((Integer) st2.pop() * (Integer) st2.pop());
} else if (e.equals('/')) {
st2.push((Integer) st2.pop()/(Integer) st2.pop());
} else {
st2.push(e);
}
}
return (Integer) st2.pop();//marks an error here
}
}
我想无论你使用'st.push'它应该是'st2.push'(当检查操作员时) –
只有最后一个去'st2'。试试看,例如,2 3 +会给你5的结果。你必须推回到同一个堆栈。 –
但它是前缀,所以它应该是+ 2 3 –