-1

problem: i am trying to take string input from files and then store it in an arraylist then trying to search specific words and removing them and the resultant output should go to another text file... this code works fine if there are only 2 elements in a list . but if i put more it showing java.lang.IndexOutOfBoundsException index:12 size 12 . i am not that good in java so pls help and sorry for any silly mistakes ...

 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();
    }
} 
jenny
  • 1
  • 1
  • 2

2 Answers2

2

Try to write your arrayList temps without capacity 10 like this:

 List<String> temps = new ArrayList<String>();
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

In java arrays are 0 based. It means that an array of size 12 has index between 0 and 11.

Modify your code with

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

because size is 12 and last valid index is 11.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56