2016-02-06 43 views
-1

問題:我試圖從文件中獲取字符串輸入,然後將其存儲在數組列表中,然後試圖搜索特定的單詞並將其刪除,並將結果輸出到另一個文本文件...如果列表中只有2個元素,此代碼可以正常工作。但如果我把更多的顯示java.lang.IndexOutOfBoundsException索引:12大小12。我不是在Java中好,所以請幫助和遺憾,對任何愚蠢的錯誤......java.lang.IndexOutOfBoundsException索引:12大小12 java

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.List; 

public class replace{ 

    public static void main(String[] args) throws Exception{ 
     String filen = "C:/Users/Damini/Desktop/hi.txt"; 
     FileReader file = new FileReader("C:/Users/Damini/Desktop/rules.txt"); 
     BufferedReader b = new BufferedReader(file); 
     PrintWriter pw = new PrintWriter(filen); 
     List<String> temps = new ArrayList<String>(10); 

     String line = b.readLine(); 
     while(line!= null) 
     { 
      temps.add(line); 
      line = b.readLine(); 

     } 
     int size = temps.size()-1; 
     for(int i=0;i<=size;i++) 
     { 
      if(temps.get(i).equals("hello")) 
      { 
       temps.remove(i); 

      } 
     } 
     pw.println(temps); 
     pw.close(); 
     System.out.println("output:"+ temps); 

     b.close(); 
    } 
} 

回答

2

嘗試寫你的arrayList臨時工沒有capacity10這樣的:

List<String> temps = new ArrayList<String>(); 
  • capacity是無需重新分配其內部結構,清單可以容納多少個元素。
0

在java中陣列0基於。這意味着,尺寸12的陣列具有索引0之間和11

for (int i = 0; i <= size; i++) 

修改您的代碼,因爲大小是12和最後一個有效索引是11。

相關問題