Java – LastIndexOf and java.lang.IndexOutOfBoundsException

LastIndexOf and java.lang.IndexOutOfBoundsException… here is a solution to the problem.

LastIndexOf and java.lang.IndexOutOfBoundsException

I

have a string CCAATA CCGT and I’m trying to get a continuous subsequence of fixed length n. Then, I want to get something like this:

The index of each subsequence in the string. 0-3, 1-4, 2-5, etc

0 thru 3 : CCAA 
1 thru 4 : CAAT 
2 thru 5 : AATA 
3 thru 6 : ATAC 
4 thru 7 : TACC 
5 thru 8 : ACCG 
6 thru 9 : CCGT 

The list size is 7. Here, I loop through the list and get the index and lastIndexOf. After 3 to 6: ATAC, I got

Exception in thread “main”
java.lang.IndexOutOfBoundsException: Index: 7, Size: 7

for (int i = 0; i < list.size(); i++) {
            System.out.println(ss.indexOf(list.get(i)) 
             + " thru " + ss.lastIndexOf(list.get(i + n - 1)) + " : " 
            + list.get(i));

Demo:

import java.util.ArrayList;

public class Subsequences {

public static void main(String[] args) {

String s = "CCAATA CCGT";
        ArrayList<String> list = new ArrayList<String>();  list of subsequence

int n = 4;  subsequences of length

String ss = s.replaceAll("\\s+", "");
        String substr = null;

for (int i = 0; i <= ss.length() - n; i++) {
            substr = ss.substring(i, i + n);
            list.add(substr);
        }

for (int i = 0; i < list.size(); i++) {
            System.out.println(ss.indexOf(list.get(i)) 
             + " thru " + ss.lastIndexOf(list.get(i + n - 1)) + " : " 
            + list.get(i));

}
    }
}

Any tips?

Solution

You don’t need to add n to lastIndexOf because you separate substring into 4. Each entry in the List consists of 4 characters. Change your index check to this

(ss.lastIndexOf(list.get(i)) + n - 1)

And finally this is what it looks like

 for (int i = 0; i < list.size(); i++) {
        System.out.println(ss.indexOf(list.get(i))
                + " thru " + (ss.lastIndexOf(list.get(i)) + n - 1) + " : "
                + list.get(i));

}

Output:

0 thru 3 : CCAA   
1 thru 4 : CAAT   
2 thru 5 : AATA   
3 thru 6 : ATAC   
4 thru 7 : TACC   
5 thru 8 : ACCG  
6 thru 9 : CCGT   

Related Problems and Solutions