我想通过单词的开头来计算 ArrayList 中每个单词的频率。例如 [cat, cog, mouse] 表示有 2 个以c开头的单词和 1 个以m开头的单词。我的代码工作正常,但字母表中有 26 个字母,如果s需要更多。有没有其他方法可以做到这一点?
public static void countAlphabeticalWords(ArrayList<String> arrayList) throws IOException
{
int counta =0, countb=0, countc=0, countd=0,counte=0;
String word = "";
for(int i = 0; i<arrayList.size();i++)
{
word = arrayList.get(i);
if (word.charAt(0) == 'a' || word.charAt(0) == 'A'){ counta++;}
if (word.charAt(0) == 'b' || word.charAt(0) == 'B'){ countb++;}
}
System.out.println("The number of words begining with A are: " + counta);
System.out.println("The number of words begining with B are: " + countb);
}