You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java开发DNA基因查找程序时for循环停在dna[2]无输出问题咨询

问题排查结果

程序不是卡在dna[2]的遍历步骤,是执行到后续元素时触发了字符串下标越界异常,导致程序直接终止运行,看起来像是卡住无输出。

错误根因

findSimpleGene方法的逻辑顺序写错了:

  • 你在还没校验startIndex(起始密码子atg的位置)、stopIndex(终止密码子taa的位置)是否合法的情况下,就提前执行了substring截取操作
  • 当DNA串里找不到atg、或者atg后面找不到taa时,indexOf会返回-1,这时候把-1传入substring当坐标,或者传入的结束坐标小于起始坐标,就会直接抛出StringIndexOutOfBoundsException中断程序
  • 你观察到的"到dna[2]就停",实际是dna[2]的结果正常输出后,处理dna[3]时触发了异常:dna[3]里atg后面没有taa,stopIndex返回-1,执行截取时直接崩溃。

修复后代码

只需要调整findSimpleGene的逻辑顺序,把截取操作放到所有合法性校验通过之后即可:

public String findSimpleGene (String dna) {
    int startIndex = dna.indexOf("atg");
    // 没找到起始密码子直接返回
    if (startIndex == -1) {
        return "Not Exist";
    }
    int stopIndex = dna.indexOf("taa", startIndex+3);
    // 没找到符合位置要求的终止密码子直接返回
    if (stopIndex == -1) {
        return "Not Exist";
    }
    // 校验基因长度是否是3的倍数
    if ((stopIndex - startIndex) % 3 == 0) {
        return dna.substring(startIndex, stopIndex+3);
    }
    return "Not Exist";
}

替换原方法后再执行testSimpleGene,就能正常遍历输出所有5个测试用例的结果,不会中途中断。

内容的提问来源于stack exchange,提问作者RaymondGuo001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 17:06:58