我必须使用堆栈来评估前缀表达式,但确实做到了,但是我不明白为什么代码无法正常工作,在编译代码时它会标记2个错误,它们是:

线程“主”中的异常java.lang.ClassCastException:无法将java.lang.String强制转换为java.lang.Integer
    在Evaluationprefix.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();
    }

}

10-08 08:18