如何将项目保存到特定数组索引的次数返回?

Joe*_*uck 2 java arrays

我有一个名为LetterCounter的课程.该类通过将字符串的字母转换为字符并将它们添加到名为counts []的数组中来处理字符串,该数组具有26个位置,0对应于'a',25对应于'z'.这就是process()方法的样子.

    public class LetterCounter
{
    private static final int[] counts = new int[26];

/**
 * Method converts letters in a String into index positions in an array.
 * 0 corresponds to a, 1 to b, 2 to c, etc.
 * 
 * @param someString A String of letters
 */
public void process(String someString)
{
    for (int i = 0; i < someString.length(); i++)
    {
        char myChar = Character.toLowerCase(someString.charAt(i));
        int index = (myChar - 'a');
        if ((index >= 0) && (index <= 25))
        {
            counts[index]++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这个类中有一个方法,我调用getMostCommon()迭代数组并确定哪个位置具有最多的存储项.它看起来像这样:

/**
 * Method finds the letter which appears most often.
 */
public char getMostCommon()
{
    int max = 0;

    for(int i = 0; i < counts.length; i++)
    {
        if(counts[i] > max)
        {
            max = i;
        }
    }

    char c = Character.toLowerCase((char)(max + 'a'));
    return c;
}
Run Code Online (Sandbox Code Playgroud)

这是测试类.我希望't'是最常见的字母,但该方法返回'o'作为最常见的字母.

public class CounterDemo1
{
    public static void main(String[] args)
    {
    //Constructs new LetterCounter called cc
    LetterCounter cc = new LetterCounter();

    //The letters in these strings will be processed into array index positions.
    cc.process("Bojack hates the troops");
    cc.process("Peanut butter is one word");
    cc.process("Use a pretty font");

    //Demonstrates printHistogram()
    cc.printHistogram();
    //Demonstrates getCount()
    System.out.println("There are " + cc.getCount('b') + " b's.");
    //Demonstrates getToalLetters()
    System.out.println("There are " + cc.getTotalLetters() + " total letters.");
    //Demonstrates getMostCommon()
    System.out.println("The most common letter is: " + cc.getMostCommon());
}
Run Code Online (Sandbox Code Playgroud)

}

Rob*_*elo 5

到目前为止,您需要存储最大字符频率的值:max 当前字符索引:i.

您正在将max与字符i的频率进行比较:if(counts[i] > max)然后将i的值分配给max:max = i;

你可能想这样做:

public char getMostCommon()
{
     int max = 0;
     int current_index = 0; // current character index
     for(int i = 0; i < counts.length; i++)
     {
          if(counts[i] > max)
          {
               max = counts[i]; // Getting the value of the frequency
               current_index = i; // And the value of the character index
          }
      }
      // Finally parsing the index
      char c = Character.toLowerCase((char)(current_index + 'a'));
      return c;
} 
Run Code Online (Sandbox Code Playgroud)