我必须使用堆栈来计算前缀表达式,我做到了,但我不明白为什么代码不能正常工作,它在我编译代码时标记了 2 个错误,它们是:
线程“main”中出现异常java.lang.ClassCastException:java.lang.String无法转换为java.lang.Integer 在评估前缀.EvaluationPreFix.EvaluationPrefix(EvaluationPreFix.java:56) 在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
}
}
最佳答案
所做的更改:
- 在main方法中,将堆栈st更改为
String
类型。 - 在EvaluationPrefix方法中,
- 将参数堆栈更改为
String
类型。 - 将堆栈 st2 更改为
Integer
类型。 - 将
equals
中的算术运算符更改为String
。
- 将参数堆栈更改为
给你,
public class EvaluationPreFix {
public static void main(String[] args) {
//1. parameterized with String
Stack<String> 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);
}
//2. parameterized with String
public static int EvaluationPrefix(Stack<String> st) {
//3. parameterized with Integer
Stack<Integer> st2 = new Stack();
while (!st.isEmpty()) {
String e = st.pop();
//4. arithmetic sign comparison to string instead
//of character
if (e.equals("+")) {
st2.push(st2.pop() + st2.pop());
} else if (e.equals("-")) {
st2.push(st2.pop() - st2.pop());
} else if (e.equals("*")) {
st2.push(st2.pop() * st2.pop());
} else if (e.equals("/")) {
st2.push(st2.pop() / st2.pop());
} else {
st2.push(Integer.valueOf(e));
}
}
return st2.pop();
}
}
关于java - 使用堆栈计算前缀表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250395/