Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

String index out of range in Java

I am aware there are multiple threads like my assignment below, but I just can't figure it out. I can't exactly figure out the mistake. Help would be appreciated.

I am trying to do this program:

enter image description here

enter image description here

Everything works fine unless I input the same chains or similar (for example ACTG and ACTG or ACTG and ACTGCCCC), when it tells me

string index out of range

This is that part of my code:

int tries=0;
int pos=-1;
int k;

for (int i=0; i<longDNA.length(); i++) {

    tries=0;
    k=i;

    for (int j=0; j<shortDNA.length(); j++) {

        char s=shortDNA.charAt(j);
        char l=longDNA.charAt(k);

        if (canConnect(s,l)) {
            tries+=1;
            k+=1;
        } 
    }

    if (tries==shortDNA.length()-1) {
        pos=i-1;
        break;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's call the two DNA strings longer and shorter. In order for shorter to attach somewhere on longer, a sequence of bases complementary to shorter must be found somewhere in longer, e.g. if there is ACGT in shorter, then you need to find TGCA somewhere in longer.

So, if you take shorter and flip all of its bases to their complements:

char[] cs = shorter.toCharArray();
for (int i = 0; i < cs.length; ++i) {
  // getComplement changes A->T, C->G, G->C, T->A,
  // and throws an exception in all other cases
  cs[i] = getComplement(cs[i]);
}
String shorterComplement = new String(cs);

For the examples given in your question, the complement of TTGCC is AACGG, and the complement of TGC is ACG.

Then all you have to do is to find shorterComplement within longer. You can do this trivially using indexOf:

return longer.indexOf(shorterComplement);

Of course, if the point of the exercise is to learn how to do string matching, you can look at well-known algorithms for doing the equivalent of indexOf. For instance, Wikipedia has a category for String matching algorithms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...