【问题标题】:Java, choose subsequenceJava,选择子序列
【发布时间】:2013-08-21 15:09:24
【问题描述】:

我的程序的一部分有问题。

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

目的是:对于外部for的每次重复,我们取text_generated的最后一个n字符,对于字母表中的每个字母,我们计算text_formatted中出现的次数n+1字符加上text_generated的最后一个n字符得到的字符;然后我们选择出现次数最多的字母并将其附加到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]);

        }

【问题讨论】:

    标签: java string vector stringbuffer


    【解决方案1】:

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

    【讨论】:

    • 但以下指令“for”控制某些 d 的出现次数[d] > 出现次数[index]
    【解决方案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 的值有关。

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多