2015-10-08 57 views
0

我寫了一個函數,它接受一個字符串文本並可以訪問包含 字符的向量v。它在文本[i]上循環。如果發現有任何字符在v中,那麼它應該採用text [i]並將其放入v中找到相同索引的v2(一個新向量)?並且出界限制的異常會向我發送任何幫助?索引超出範圍例外,我寫的函數是關閉的

 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); 



     } 
+0

是'text'和'v'的價值,你輸入的內容?例如 – silentprogrammer

+0

text = aaaabbbccc,v = abc。 – zeyad

+0

其應該是一個壓縮文件功能 – zeyad

回答

1

使用

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

,而不是

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

問題不在循環中我發誓 – zeyad

0

變化

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

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

這很重要,因爲i -- i不會產生相同的結果,並使for以不同方式處理索引。

這是這裏解釋:What is the difference between ++i and i++?(其他語言的問題,但有關我的反應++ VS ++我是一樣的)