質問

I have a problem with a part of my program.

In the following code, there are 27 letters in our alphabet.

The aim is: for every repetition of the outer for, we take the last n characters of text_generated, and for every letter of the alphabet, we count the number of occurrences in text_formatted of the n+1 characters obtained by adding the character to the last n characters of text_generated; then we choose the letter with the most occurrences and append it to text_generated. The result I obtain is something like:

***aaaaaaaaaaaaaaaaaaa

why?

The code:

        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

The result that you get***aaaaaaaaaaaaaaaaaaa and this loop

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

indicates that that the every item in the occurrences array is 0. This means that your algorithm defaults to appending array[0] to the text_generated string. This means that the problem is in this block

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;
}

Possible problems:

  • The loop is never entered, text_formatted.length() - n - 1 results in a negative value.
  • The if always evaluates to false.

In both cases the problem is most likely related to the values of n and text_formatted.

他のヒント

You always set your index = 0, so first letter in array[] is chosen, which always is a.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top