我有一个名为 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]++;
}
}
}
我在这个类中有一个方法,我称之为 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;
}
这是测试类。我预计“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());
}
}
最佳答案
您需要存储到目前为止的最大字符频率值: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;
}
关于java - 如何返回某个项目保存到特定数组索引的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620939/