我一直致力于開發用于在 DNA 鏈中查找基因的 Java 編程。我的問題是為什么 for 回圈在 dna[2] 結束并且輸出停留在第三個 String 并且沒有回傳更多結果。以下是代碼:
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);
}
}
}
謝謝!
uj5u.com熱心網友回復:
因為dna[3] = "acggggtttgaagaatgaaccaat"
startIndex 是 14 而 stopIndex 是 -1,因為沒有“taa”
之后你會發現subString(14,2)在這種情況下會拋出例外。
方法拋出“java.lang.StringIndexOutOfBoundsException”例外
uj5u.com熱心網友回復:
為了
dna[3] = "acggggtttgaagaatgaaccaat";
您的代碼正在引發StringIndexOutOfBoundsException例外,因此您看到它不再推進到 for 回圈的下一次迭代:
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.
為了避免這種情況,你可以在呼叫 substring 之前檢查 startIndex 總是小于 stopIndex:
if(startIndex < stopIndex && startIndex!=-1 && stopIndex < dna.length()){
result = dna.substring(startIndex, stopIndex 3);
..}
uj5u.com熱心網友回復:
問題在于您撰寫findSimpleGene方法的方式,特別是當您嘗試檢索stopIndex. 事實上,在這種情況下,startIndex可能在字串的結尾或結尾之前少于 3 個字符,因此當您執行時,dna.indexOf("taa", startIndex 3)您可能會超出給定String. 此外,計算stopIndex何時startIndex可能是 -1 沒有什么意義。
您可以在計算之前添加一個檢查,例如三元運算子,它控制startIndex不是 -1 并且記入 3 仍然使它在給定的String. 附帶說明一下,只是為了減少您的代碼,您可以已經設定result為“不存在”并僅在子字串可以發生時更新它(更少的 if-else 分支和更好的可讀性)。
public String findSimpleGene(String dna) {
String result = "Not Exist";
int startIndex = dna.indexOf("atg");
int stopIndex = startIndex >= 0 && startIndex 3 < dna.length() ? dna.indexOf("taa", startIndex 3) : -1;
if (startIndex != -1 && stopIndex != -1 && (stopIndex - startIndex) % 3 == 0) {
result = dna.substring(startIndex, stopIndex 3);
}
return result;
}
輸出
DNA strand:cccatggggtaaaaatgataataggagagagagagagagttt
Gene:atggggtaa
DNA strand:ccatggggtctaaataataa
Gene:Not Exist
DNA strand:atggggcgtaaagaataa
Gene:Not Exist
DNA strand:acggggtttgaagaatgaaccaat
Gene:Not Exist
DNA strand:acggggtttgaagaatgaaccaataacga
Gene:atgaaccaataa
這里還有一個測驗上面代碼的鏈接:
https://www.jdoodle.com/iembed/v0/s7F
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488807.html
