设计一个关键字统计程序:利用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) + "次");
        }
    }
}
相关推荐
我最厉害。,。28 分钟前
Windows权限提升篇&数据库篇&MYSQL&MSSQL&ORACLE&自动化项目
数据库·mysql·sqlserver
远方160934 分钟前
20-Oracle 23 ai free Database Sharding-特性验证
数据库·人工智能·oracle
nenchoumi31191 小时前
AirSim/Cosys-AirSim 游戏开发(一)XBox 手柄 Windows + python 连接与读取
windows·python·xbox
GoodStudyAndDayDayUp1 小时前
初入 python Django 框架总结
数据库·python·django
星辰大海的精灵1 小时前
基于Dify+MCP实现通过微信发送天气信息给好友
人工智能·后端·python
精灵vector1 小时前
Agent短期记忆的几种持久化存储方式
人工智能·python
北京_宏哥1 小时前
🔥Python零基础从入门到精通详细教程4-数据类型的转换- 上篇
前端·python·面试
乾巫宇宙国监察特使1 小时前
Python的设计模式
python·测试
Hockor2 小时前
写给前端的 Python 教程四(列表/元组)
前端·后端·python
这里有鱼汤2 小时前
熟练掌握MACD这8种形态,让你少走三年弯路(附Python量化代码)| 建议收藏
后端·python