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");
}
}
From what I understand,
i
represents an index in the string. However, here:you are using at as an index to your vector. My guess is what you meat was: