Home > Software design >  Why the for loop ends up at dna[2]"
Why the for loop ends up at dna[2]"

Time:06-11

I've been working on java programming developed to find the gene in DNA strands. My question is why the for loop ends up at dna[2] and the output stucked at the third String and no more results are returned. The following is the code:

import edu.duke.*;
import java.io.*;


public class Part1 {
        public String findSimpleGene (String dna) {
            String result = "";
            int startIndex = dna.indexOf("atg");
            int stopIndex = dna.indexOf("taa", startIndex 3);
            result = dna.substring(startIndex, stopIndex 3);
            if (startIndex != -1 
            && stopIndex != -1 
            && (stopIndex - startIndex) % 3 ==0) {
                return result;
            }
            else {
                return "Not Exist";
            }
            
        }
        public void testSimpleGene () {
            String dna[] = new String[5];
            dna[0] = "cccatggggtaaaaatgataataggagagagagagagagttt";
            dna[1] = "ccatggggtctaaataataa";
            dna[2] = "atggggcgtaaagaataa";
            dna[3] = "acggggtttgaagaatgaaccaat";
            dna[4] = "acggggtttgaagaatgaaccaataacga";
            for (int i=0; i < 5; i  ) {
            String result = findSimpleGene(dna[i]);
            System.out.println("DNA strand:"   dna[i]);
            System.out.println("Gene:"   result);
        }
        }
}

Thanks!

CodePudding user response:

For dna[3] = "acggggtttgaagaatgaaccaat"
startIndex is 14 and stopIndex is -1 since there is no "taa"
After that you are finding subString(14,2) which will throw below exception in this case.
Method threw 'java.lang.StringIndexOutOfBoundsException' exception

CodePudding user response:

For

dna[3] = "acggggtttgaagaatgaaccaat";

Your code is throwing StringIndexOutOfBoundsException exception & hence you sees it is no longer advancing to next iteration of for loop :

int startIndex = dna.indexOf("atg"); // gives 14
int stopIndex = dna.indexOf("taa", startIndex   3); // gives -1
result = dna.substring(startIndex, stopIndex   3); //throws `StringIndexOutOfBoundsException` because startIndex is larger than stopIndex.

To avoid this kind of scenario, you can check startIndex is always less than stopIndex before calling substring:

if(startIndex < stopIndex && startIndex!=-1 &&  stopIndex < dna.length()){
 result = dna.substring(startIndex, stopIndex   3);
 ..}
  • Related