21xrx.com
2025-03-22 13:57:34 Saturday
文章检索 我的文章 写文章
Java实现短文统计单词的程序
2023-06-11 12:14:20 深夜i     --     --
Java 统计 单词

在日常编程中,我们都可能会遇到统计文本中单词数量的需求。而使用Java语言来实现这个功能是非常简单的。

下面是一个Java程序,它可以读取一段文本,并统计其中每个单词的数量:

import java.util.HashMap;
import java.util.Scanner;
public class WordCount {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("请输入一段文本:");
    String text = input.nextLine();
    String[] words = text.split("\\s+");
    HashMap
  wordCount = new HashMap<>();
 
    for (int i = 0; i < words.length; i++) {
      String word = words[i].toLowerCase();
      if (wordCount.containsKey(word)) {
        int count = wordCount.get(word);
        wordCount.put(word, count + 1);
      } else {
        wordCount.put(word, 1);
      }
    }
    for (String word : wordCount.keySet()) {
      int count = wordCount.get(word);
      System.out.println(word + ": " + count);
    }
  }
}

我们先通过Scanner类来读取用户输入的文本,然后使用split()方法将文本分割成单个单词。接着,我们使用HashMap类来统计每个单词的数量。最后,我们遍历hashmap来输出每个单词的数量。

现在,让我们来试试用这个程序来统计一段文本中的单词数量:

请输入一段文本:

Java is a popular programming language. It is used to build web applications, desktop applications, mobile applications, and video games.

java: 1

is: 1

a: 1

popular: 1

programming: 1

language.: 1

it: 1

used: 1

to: 1

build: 1

web: 1

applications,: 1

desktop: 1

applications: 1

mobile: 1

and: 1

video: 1

games.: 1

我们可以看到,程序成功地统计出了这段文本中每个单词的数量。

  
  

评论区