我不确定我的代码是否有问题,但是当我尝试使用长度超过 50 个字符的字符串运行代码时,BlueJ 会尝试永远运行该程序,但控制台永远不会出现。我让它运行了一个小时左右仍然没有结果。
我尝试过直接在程序中输入各种字符串,似乎输入较短的 DNA 链工作正常,但在达到一定长度后,程序永远不会执行,我不确定问题可能是什么,因为没有错误显示消息或异常。
package com.company;
public class problem3 {
public static void main(String[] args) {
new problem3().printAllGenes("CAATGCTGATAGTAATGGTATTATGATATGTAGTGGGATTTAGAGGATGCGCGCAGCCGATGACGAGCGACGATGCTAA");
}
public int findStopCodon(String dnaStr, int startIndex, String stopCodon) {
int currIndex = dnaStr.indexOf(stopCodon, startIndex + 3);
while (currIndex != -1) {
int diff = currIndex - startIndex;
if (diff % 3 == 0) {
return currIndex;
} else {
currIndex = dnaStr.indexOf(stopCodon, currIndex+1);
}
}
return dnaStr.length();
}
public String findGene(String dna, int where) {
int startIndex = dna.indexOf("ATG", where);
if (startIndex == -1) {
return "";
}
int taaIndex = findStopCodon(dna, startIndex, "TAA");
int tagIndex = findStopCodon(dna, startIndex, "TAG");
int tgaIndex = findStopCodon(dna, startIndex, "TGA");
int minIndex = 0;
if (taaIndex == -1 || (tgaIndex != -1 && tgaIndex < taaIndex)) {
minIndex = tgaIndex;
} else {
minIndex = taaIndex;
}
if (minIndex == -1 || (tagIndex != -1 && tagIndex < minIndex)) {
minIndex = tagIndex;
}
if (minIndex == -1) {
return "";
}
if (minIndex + 3 > dna.length()) {
return "";
}
return dna.substring(startIndex, minIndex + 3);
}
public void printAllGenes(String dna) {
int startIndex = 0;
while (true) {
System.out.println("yes");
String currentGene = findGene(dna, startIndex);
if (currentGene.isEmpty()) {
break;
}
System.out.println(currentGene);
startIndex = dna.indexOf(currentGene, startIndex) + currentGene.length();
}
}
}
该程序应该通过查找起始密码子 (ATG) 和终止密码子 (TAA、TAG、TGA) 来获取一条 DNA 链并导出基因。要运行该程序,我将使用 String dna = "CAATGCTGATAGTAATGGTATTATGATATGTAGTGGGATTTAGAGGATGCGCGCAGCCGATGACGAGCGACGATGCTAA"调用 printAllGenes() 方法。
最佳答案
你可能需要改变
currIndex = dnaStr.indexOf(stopCodon, currIndex);
在findStopCodon
中到
currIndex = dnaStr.indexOf(stopCodon, currIndex + 1);
否则您将始终找到相同的 currIndex
并且永远不会退出 while
循环。
关于java - 为什么 blueJ 试图永远执行我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157915/