【发布时间】:2015-10-19 00:37:14
【问题描述】:
我有一个程序,用户可以输入一个句子,它可以将每个单词分成一个数组。另外,我需要计算每个单词的频率。例如,Apple is an apple is a phone,结果是Apple-1;是-2;一个-1;一个-1;电话 1。
请帮我解决这个问题,我不知道如何计算每个单词的频率。
这是我的代码:
public static void main(String[] args)
{
while (true)
{
System.out.println("Enter a sentence:");
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
if (sentence.isEmpty()) // quit the program when user enter an empty string
{
break;
}
else
{
StringTokenizer st = new StringTokenizer(sentence);
List<String> sentenceElement = new ArrayList<String>();
while (st.hasMoreTokens())
{
sentenceElement.add(st.nextToken());
}
System.out.println(sentenceElement);
}
}
非常感谢!!
【问题讨论】:
-
你为什么要使用无限循环?
-
当用户输入一个空字符串时,退出程序。
-
这个问题来自here。在那个问题中,有一个实现
HashMap的答案。你试过了吗?