【发布时间】:2015-10-18 17:02:46
【问题描述】:
我对我的作业有几个问题。
赋值是让用户输入一个句子,程序统计每个单词的出现频率,当用户输入一个空字符串时,退出程序。此外,该程序区分大小写。例如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);
while (st.hasMoreTokens())
{
List<String> sentenceElement = new ArrayList<String>();
sentenceElement.add(st.nextToken());
}
System.out.println(sentenceElement);
}
}
我有几个问题。
- 我尝试将所有标记保存到一个名为 sentenceElement 的数组中,并尝试输出,但失败了。编译器显示
错误:找不到符号 System.out.println(sentenceElement);
- 如何计算每个词出现的频率?
非常感谢,非常感谢您的回答和解决方案。
【问题讨论】:
-
不要使用 StringTokenizer,它是遗留的,不应再使用。引用 StringTokenizer api: StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人使用 String 的 split 方法或 java.util.regex 包。
-
检查Scope of Local Variable Declarations。对于第 2 部分,使用
Map存储单词及其出现是个好主意 -
以这种方式完成作业是一种糟糕的方式。 :P。请自行尝试。
-
@NinadIngole 感谢您的 cmets,我已经为此工作了两天,请到这里寻求帮助。