有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

string Java,选择subsequence

我的程序有一部分有问题

在下面的代码中,我们的字母表中有27个字母

目的是:对于外部for的每一次重复,我们取text_generated的最后n个字符,对于字母表的每个字母,我们计算通过将字符添加到text_generated的最后n个字符中text_formatted出现的次数;然后我们选择出现次数最多的字母,并将其附加到text_generated。我得到的结果是:

***aaaaaaaaaaaaaaaaaaa

为什么

代码:

        int index;
        int[] occurrences = new int[27];
        int count;
        for(int a = 0; a < m; a++){     // m is the number of characters the user wants to add              

            for(int b = 0; b < 27; b++){
                StringBuffer curr_word = new StringBuffer(text_generated.substring(text_generated.length()-n, text_generated.length()));
                count = 0;
                for(int c = 0; c <= text_formatted.length() -n-1;c++){
                    if(text_formatted.substring(c,c+n+1).equals(curr_word.append(array[b])))
                    count += 1;
                }
                occurrences[b] = count;
            }

            index = 0;
            for(int d = 1; d < 27; d++){
                if(occurrences[d] > occurrences[index])
                    index = d;
            }

            text_generated = text_generated.append(array[index]);

        }

共 (2) 个答案

  1. # 1 楼答案

    您总是设置index = 0,所以选择数组[]中的第一个字母,它总是a

  2. # 2 楼答案

    结果是***aaaaaaaaaaaaaaaaaaa和这个循环

    index = 0;
    for(int d = 1; d < 27; d++){
      if(occurrences[d] > occurrences[index])
        index = d;
    }
    

    指示引用数组中的每个项都是0。这意味着您的算法默认将array[0]附加到text_generated字符串。这意味着问题出在这个街区

    for(int c = 0; c <= text_formatted.length() -n-1;c++){
      if(text_formatted.substring(c,c+n+1).equals(curr_word.append(array[b])))
        count += 1;
    }
    

    可能的问题:

    • 循环永远不会进入,text_formatted.length() - n - 1结果为负值
    • if的计算结果总是false

    在这两种情况下,问题很可能与ntext_formatted的值有关