设计一个关键字统计程序:利用HashMap存储关键字统计信息,对用户输入的关键字进行个数统计。

思路分析

首先,在KeywordCounter类中,定义了一个包含所有Java关键字的字符串数组KEYWORDS,用于存储所有关键字。然后创建了一个Scanner对象input,用于从标准输入读取用户的输入。接下来创建了一个StringBuilder对象sb,用于存储读取的每一行输入内容。同时,还创建了一个HashMap对象map,用于存储每个关键字的出现次数。

在一个无限循环中,通过input.nextLine()方法逐行读取用户输入的内容,并判断是否等于"exit",如果是则跳出循环。否则,将读取到的内容传递给processLine()方法进行处理,并将处理结果添加到sb中。

接下来,将sb转换为一个字符串content。对content进行预处理,首先调用removeCommentsAndStrings()方法去除注释和字符串,并将处理后的内容重新赋值给content。然后使用正则表达式content.replaceAll("[^a-zA-Z]", " ")将非字母字符替换为空格,得到只包含字母的单词。

content按照空格进行分割,将分割后的单词存储在words数组中。接着调用countKeywords()方法,遍历words数组,如果单词在KEYWORDS数组中,则将该单词作为键,存储在map中,并增加对应关键字的计数。

最后,调用printKeywordCounts()方法,对map中的结果进行排序,并逐个输出关键字及其出现次数。

运行结果示例

代码

java 复制代码
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class KeywordCounter {

    private static final String[] KEYWORDS = {"abstract", "assert", "boolean", "break", "byte", "case", "catch",
            "char", "class", "const", "continue", "default", "do", "double", "else",
            "enum", "extends", "false", "final", "finally", "float",
            "for", "goto", "if", "implements", "import", "instanceof",
            "int", "interface", "long", "native", "new", "null", "package",
            "private", "protected", "public", "return", "short", "static",
            "strictfp", "super", "switch", "synchronized", "this", "throw",
            "throws", "transient", "true", "try", "void", "volatile", "while"};

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        Map<String, Integer> map = new HashMap<>();

        while (true) {
            String line = input.nextLine();
            if ("exit".equals(line)) {
                break;
            }
            sb.append(processLine(line)).append(" ");
        }

        String content = sb.toString();
        content = removeCommentsAndStrings(content);
        content = content.replaceAll("[^a-zA-Z]", " ");

        String[] words = content.split("\\s+");
        countKeywords(words, map);

        printKeywordCounts(map);
    }

    private static String processLine(String line) {
        if (line.matches("(.*)//(.*)")) {
            return line.split("//", 2)[0];
        } else {
            return line;
        }
    }

    private static String removeCommentsAndStrings(String content) {
        content = content.replaceAll("/\\*(?:.|[\\n\\r])*?\\*/", " ");
        content = content.replaceAll("\".*?\"", " ");
        return content;
    }

    private static void countKeywords(String[] words, Map<String, Integer> map) {
        for (String word : words) {
            if (Arrays.asList(KEYWORDS).contains(word)) {
                map.put(word, map.getOrDefault(word, 0) + 1);
            }
        }
    }

    private static void printKeywordCounts(Map<String, Integer> map) {
        Set<String> keySet = map.keySet();
        String[] keys = keySet.toArray(new String[0]);
        Arrays.sort(keys);
        for (String key : keys) {
            //System.out.println(map.get(key) + "\t" + key);
        	System.out.println(key + ":" + "\t" + map.get(key) + "次");
        }
    }
}
相关推荐
凛铄linshuo4 分钟前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习
陈卓4106 分钟前
MySQL-主从复制&分库分表
android·mysql·adb
牛客企业服务7 分钟前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
胡斌附体19 分钟前
linux测试端口是否可被外部访问
linux·运维·服务器·python·测试·端口测试·临时服务器
IT项目管理40 分钟前
达梦数据库DMHS介绍及安装部署
linux·数据库
你都会上树?1 小时前
MySQL MVCC 详解
数据库·mysql
大春儿的试验田1 小时前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
likeGhee1 小时前
python缓存装饰器实现方案
开发语言·python·缓存
项目題供诗1 小时前
黑马python(二十五)
开发语言·python
读书点滴1 小时前
笨方法学python -练习14
java·前端·python