Hello, I'm facing another problem with vectors, this time with the problem of converting infix to postfix. The compile process completes, but I recieve an error after I enter the infix expression. Here is the exact error I recieve:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43 >= 2
at java.util.Vector.removeElementAt(Vector.java:511)
at vector4.InToPost(vector4.java:22)
at vector4.main(vector4.java:79)
Process completed.
I don't really know what is wrong with my code and why I am recieving the error. Here is my code:
import java.util.*;
public class vector4
{
public static String InToPost(String infixString)
{
//operator vector initialized
Vector<Character> opVect = new Vector<Character>();
//postfixString initialized as empty
String postfixString = "";
//scan infix strring and take appropriate action
for(int index = 0; index<infixString.length(); ++index)
{
char chValue = infixString.charAt(index);
if(chValue == '(')
opVect.add('(');
else if(chValue == ')')
{
Character oper = opVect.lastElement();
while(!(oper.equals('(')) && !(opVect.isEmpty()))
{
postfixString += oper.charValue();
opVect.removeElementAt(opVect.lastElement());
oper = opVect.lastElement();
}//end while loop
opVect.removeElementAt(opVect.lastElement());
}//end else if
else if(chValue == '+' || chValue == '-')
{
if(opVect.isEmpty()) //operatorStack is empty
opVect.add(chValue);
else //current operatorStack is not empty
{
Character oper = opVect.lastElement();
while(!(opVect.isEmpty() || oper.equals(new Character('(')) || oper.equals(new Character(')'))))
{
opVect.removeElementAt(opVect.lastElement());
postfixString += oper.charValue();
}//ends while loop
opVect.add(chValue);
}//end else
}//end else if
else if(chValue == '*' || chValue == '/')
{
if(opVect.isEmpty())
opVect.add(chValue);
else
{
Character oper = opVect.lastElement();
while(!oper.equals(new Character('+')) && !oper.equals(new Character('-')) && !opVect.isEmpty())
{
opVect.removeElementAt(opVect.lastElement());
postfixString += oper.charValue();
}//end while loop
opVect.add(chValue);
}//end else
}//end else if
else
postfixString += chValue;
}//end for loop
while(!opVect.isEmpty())
{
Character oper = opVect.lastElement();
if(!oper.equals(new Character('(')))
{
opVect.removeElementAt(opVect.lastElement());
postfixString += oper.charValue();
}//end if
}//end while
return postfixString ;
}//terminates text of InToPost method
public static void main(String[]args)
{
Vector<Character> myvect = new Vector<Character>();
System.out.println("Enter a string in infix notation");
Scanner scan = new Scanner(System.in);
String str="";
str=scan.next();
InToPost(str);
System.out.println(str);
}//terminates text of main method
}//terminates text of vector4 class
Thanks in advance for any help.