2

我尝试从头开始编写此代码、编码并运行它,但它似乎不起作用。这被分配为课堂上的实验室工作。要求是: 使用堆栈和堆栈操作(用户定义)实现后缀评估。我认为我的程序的算法是正确的,但它总是给我错误的答案。这是我的代码。

public class StackApplication {

    public static class Stack<T> {

        private int top = 0;
        private final static int stackMax=100;
        // highest index of stk array
        private Object[] stk = new Object[stackMax+1];
        //Elements must be cast back.

        public Stack() { // constructor
        }

        public boolean isEmpty(){
            if (top==0) return true;
            else return false;
        }

        public void push(T el) {
            if(top==stackMax)
                System.out.println("Stack push overflow error");
            else top=top+1;
            stk[top]=el;
        }

        public T pop(){
            if(isEmpty()){
                System.out.println("Stack push underflow error");
                return null;
            }
            else top=top-1;
            return(T)stk[top+1];
        }

        public T top(){
            if(isEmpty()){
                //System.out.println("Stack empty");
                return null;
            }
            else return (T)stk[top];
        }
    }
    public static boolean isOperator(char c){
        return(c=='+' || c=='-' || c=='/' || c=='*' || c=='^');
    }
    public static double evaluate(double x, char o, double y) {

        double result=0;
        switch(o) {
            case '+' : result=x+y; break;
            case '-' : result=x-y; break;
            case '*' : result=x*y; break;
            case '/' : result=x/y; break;
            case '^' : result=Math.pow(x, y);  break;
            default : break;    
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner console=new Scanner(System.in);
        Stack<Double> s=new Stack<Double>();

        System.out.println("Input Postfix form to evaluate:");
        String inp=console.nextLine();
        char[] chararray=inp.toCharArray();
        double b,a;

        for(int i=0; i<chararray.length; i++) {
            if(!isOperator(chararray[i]))
                s.push((double)chararray[i]);
            else {
                b=s.pop();
                a=s.pop();
                double c=evaluate(a, chararray[i], b);
                s.push(c);
            }
        }
        System.out.println(" " +s.pop());
    }
}

示例输出:输入后缀形式以评估:

23+ (Input)
101.0  (Output)
5.0 (Expected output) 
4

2 回答 2

1

问题出在这里:s.push((double)chararray[i]);。你不能转换chardouble这种方式。您现在正在使用2and的 ascii 代码3

50(ascii code of 2) + 51(ascii code of 3) = 101

像这样做:s.push((double)(chararray[i] - '0'));

于 2011-08-30T13:52:31.347 回答
1

您正在添加 2 和 3 的 ASCII 代码,而不是 2 和 3。

2 的代码是 50,3 的代码是 51,所以你的 out 是 101,在这种情况下是正确的。

推的时候,推chararray[i]-'0'。这将解决您的问题。

于 2011-08-30T13:56:20.913 回答