0

i wrote a function that take a string text and can access vector v that contains character. it loops on the text[i]. if found any char that is in v, then it should take text[i] and put it in the v2(a new vector) with the same index found in v? and out of bound exception is printed to me any help?

     public void encode( StringBuffer text) // need test
       {
           int temp,temp3;
           boolean t;
           String temp2;
           int j=0;
           int sizeoftext=text.length()-1;

           do
           {
           for(int i=v.size()-1;i>-1;--i) // loop on text
           {
               temp=(v.elementAt(i)).length();// length of the longest word in dictionary
               temp2=text.substring(j, j+temp); //string with the same length of temp
               if((v.elementAt(i).equals(temp2)))// check if they r equal
                   {   

 HERE IS THE PROBLEM          >>            v2.add(i,temp2); // if yes add it to v2
                       temp3=temp+1;// increase size to take the nxt char
                       v.addElement(text.substring(j,temp3)); //add it to the dictionay
                      // v2.trimToSize();
                      // v.trimToSize();
                   }

           }

           temp3=temp=0;
           ++j;
           --sizeoftext;


           }while(sizeoftext>-1);



       }
zeyad
  • 43
  • 3

2 Answers2

1

Use

for(int i=v.size()-1;i>=0;i--) 

instead of

for(int i=v.size()-1;i>-1;--i)
mystery
  • 875
  • 6
  • 16
0

Change

for(int i=v.size()-1;i>-1;--i) 

to

for(int i=v.size()-1;i>=0;i--) 

This is important because i-- and --i does not produce the same result and make the for to process in different manner the indexes.

This is explained here: What is the difference between ++i and i++? (Other language question but the response about i++ vs ++i is the same)

Community
  • 1
  • 1
Dubas
  • 2,855
  • 1
  • 25
  • 37