使用StringTokenizer计算每个单词的频率

时间:2015-10-18 17:02:46

标签: java arrays tokenize

关于我的任务我几乎没有问题。

分配是让用户输入一个句子,程序计算每个单词的频率,当用户输入空字符串时,退出该程序。此外,该程序区分大小写。例如, Apple是苹果手机,结果是 Apple-1;是-2;一个-1; A-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);
        }
  }

我几乎没有问题。

  1. 我尝试将所有令牌保存到名为sentenceElement的数组中,并尝试输出,但失败了。编译器显示
  2.   

    错误:找不到符号               的System.out.println(sentenceElement);

    1. 我如何计算每个单词的频率?
    2. 非常感谢,我非常感谢您的回答和解决方案。

2 个答案:

答案 0 :(得分:0)

  1. 我如何计算每个单词的频率?
  2. 使用HashMap将单词存储为键,将计数存储为值。然后循环遍历所有单词,并首先从hashmap获取单词作为键,如果它返回null然后将字母添加到值为1的hashmap,如果相同的键进入循环,则hashmap的get将不返回null它将返回旧计数,即1,不要将它增加到2,并在完成所有单词后再次将其存储回来,你在hashmap中有计数只需迭代它并打印key-&gt;值。

答案 1 :(得分:0)

您可以使用

将输入转换为令牌
    String tokens[]=input.split(" ");

现在接下来是计算每个Word的频率。您可以使用Hashmap。

HashMap < String, Integer > hmap = new HashMap < Integer, String > ();
for (str: tokens) {
    if (hmap.get(str) == null) hmap.put(str, 1);
    else hmap.put(str, hmap.get(str) + 1);
}
Iterator it = hmap.iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry) it.next();
    System.out.println(pair.getKey() + " = " + pait.getValue());
    it.remove();
}
相关问题