【问题标题】:Using HashMaps to find string frequencies使用 HashMaps 查找字符串频率
【发布时间】:2017-08-19 16:24:48
【问题描述】:

我的代码旨在从包含 lonf DNA 字符串的文件中找到最常见的密码子(即 CTAAATCGATGGCGATGATAAATG...)。从初始位置pos 开始,每三个字符组成一个密码子。我遇到的问题是,每当我运行代码时,它都会告诉我字符串索引超出范围。我知道问题出在这条线上

str = line.substring(idx, idx + 2);

但不知道如何解决。另外,我不确定我是否正确计算频率。我需要增加多次看到的每个键的值。

public static void findgene(String line){
            int idx, pos;
            int[] freq = new int[100];
            String str;

            //pos is the position to start at
            pos = 0;
            idx = pos;

            for(int i = 0; i < line.length(); i++){
                if(idx >= 0){
                    //makes every three characters into a codon
                    str = line.substring(idx, idx + 2);
                    //checks if the codon was previously seen
                    if(genes.containsKey(str)){
                        genes.put(str, freq[i]++);
                    }
                    idx = idx + 2;
                }
            }
}

【问题讨论】:

    标签: java string hashmap substring


    【解决方案1】:

    您在循环的每次迭代中将 idx 递增 2。但是,你没有对idx的上限做任何限制。

    因此substring()函数的参数很快就超出了该行的范围:

    str = line.substring(idx, idx + 2);
    

    您需要做的是将条件更改为:

    if(idx+2<=line.length()){
        //code here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多