1

Here is my code for converting infix to posfix expression. The problem is in the conversion method. I am getting error on line 21.

Error-ab+ Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 >= 0

at java.util.Vector.elementAt(Unknown Source)
at infixpostfix.conversion(infixpostfix.java:22)
at infixpostfix.main(infixpostfix.java:77)

for the current input.

I think that this error appears because I am trying to access i when its exceeding the length of my string. But how is it possible when my i's value is being governed by the for loop?

Code:-

import java.util.Stack;
public class infixpostfix {

    Stack<Character> st = new Stack<Character>();

    void conversion(String e){


        for(int i = 0 ; i < e.length() ; i++){

            if(isOp(e.charAt(i)) ){

                if(st.isEmpty()){

                    st.push(e.charAt(i));
                }

                else{
                    while(!st.isEmpty() && checkPrec(st.peek())<=checkPrec(e.charAt(i))){
                        System.out.println(st.pop());
                    }
                    st.push(st.elementAt(i));
                }
            }

            else{

                System.out.print(e.charAt(i));
            }

        }

        while(!st.isEmpty()){

            System.out.print(st.pop());

        }
    }

    int checkPrec(char o){

        switch(o){

        case '+':
        case '-':

            return 1;

        case '*':
        case '/':

            return 2;

        default:

            return -1;
        }
    }

    boolean isOp(char c){

        if(c=='+' || c=='-' || c=='/' || c=='*'){

            return true;
        }

        else{

            return false;
        }
    }

    public static void main(String args[]){

        infixpostfix obj = new infixpostfix();

        obj.conversion("a+b-c/d*f");
    }
}
4

1 回答 1

0

据我了解,i表示字符串中的索引。但是,这里:

st.push(st.elementAt(i));

您正在使用 at 作为向量的索引。我的猜测是你的肉是什么:

st.push(e.charAt(i));
于 2016-12-25T17:07:32.353 回答