以下是Java代码:

import java.util.*;

public class WordCount {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一行数据:");
        String line = scanner.nextLine();
        String[] words = line.split("\\s+"); // 以空白字符为分隔符,拆分字符串成单词数组
        Map<String, Integer> wordCount = new HashMap<>(); // 用HashMap来存储单词及其出现次数
        for (String word : words) {
            if (wordCount.containsKey(word)) { // 如果单词已经存在于HashMap中
                int count = wordCount.get(word); // 获取其出现次数
                wordCount.put(word, count + 1); // 将出现次数加1后存回HashMap
            } else {
                wordCount.put(word, 1); // 如果单词不存在于HashMap中,则将其加入HashMap,出现次数为1
            }
        }
        System.out.println("不同的单词数为:" + wordCount.size()); // 输出不同的单词数
    }
}
java从键盘上面读入一行数据利用集合类来统计不同的单词数

原文地址: https://www.cveoy.top/t/topic/b0Ql 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录