Java、统计每个关键字的出现次数

 

package set;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class Exercise21_10 {
    public static void main(String[] args) throws IOException {
        System.out.print("Enter a file: ");
        File file = new File(new Scanner(System.in).nextLine());

        if (!file.exists())
            System.out.println("File " + file + " does not exist");
        else if (!file.isFile())
            System.out.println("Not a file");
        else {
            int count = 0;
            Set<Map.Entry<String, Integer>> entrySet = countKeywords(file).entrySet();
            for (Map.Entry<String, Integer> entry: entrySet) {
                count += entry.getValue();
                System.out.println(String.format("%-10s%10d", entry.getKey(), entry.getValue()));
            }
            System.out.println("count = " + count);
        }
    }

    public static Map<String, Integer> countKeywords(File file) throws IOException {
        Set<String> keywordSet = getKeywordSet();
        Map<String, Integer> map = new TreeMap<>();

        try(Scanner input = new Scanner(file)) {
            while (input.hasNext()) {
                String word = input.next();

                if (word.contains("\"") && !word.matches(".*(\").*")) {
                    word = input.next();
                    while (input.hasNext() && !word.contains("\""))
                        word = input.next();
                    word = input.next();
                }
                if (word.contains("/*") && !word.matches("\".*/\\*\".*"))  {
                    word = input.next();
                    while (input.hasNext() && !word.contains("*/"))
                        word = input.next();
                    word = input.next();
                }
                if (word.contains("//")) {
                    input.nextLine();
                    if (input.hasNext())
                        word = input.next();
                }

                if (keywordSet.contains(word)) {
                    if (!map.containsKey(word))
                        map.put(word, 1);
                    else
                        map.put(word, map.get(word)+1);
                } else {
                    for (String s: keywordSet) {
                        for (String s1 : word.split("[ ().]"))
                            if (s1.matches(s)) {
                                if (!map.containsKey(s))
                                    map.put(s, 1);
                                else
                                    map.put(word, map.get(s) + 1);
                            }
                    }
                }
            }
        }

        return map;
    }

    /** 返回关键字集合 */
    public static Set<String> getKeywordSet() {
        String[] keyWordString = {"abstract", "assert", "boolean", "break", "byte", "case", "catch",
                "char", "class", "const", "continue", "default", "do", "double", "else", "enum",
                "extends", "for", "final", "finally", "float", "goto", "if", "implements", "import",
                "instanceof", "int", "interface", "long", "native", "new", "package", "private",
                "protected", "public", "return", "short", "static", "strictfp", "super", "switch",
                "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile",
                "while", "true", "false", "null"};
        Set<String> keywordSet = new HashSet<>(Arrays.asList(keyWordString));
        return keywordSet;
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Java程序,可以实现输入源码并统计关键字出现次数的功能: ```java import java.util.*; public class KeywordCounter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 读取源码 System.out.println("请输入Java源码:"); String sourceCode = scanner.nextLine(); // 判断输入是否合法 if (sourceCode.trim().isEmpty()) { System.out.println("输入不合法"); return; } // 将源码转换为单词列表 List<String> words = Arrays.asList(sourceCode.split("\\W+")); // 统计关键字出现次数 Map<String, Integer> keywordCounts = new TreeMap<>(); for (String word : words) { if (isKeyword(word)) { keywordCounts.put(word, keywordCounts.getOrDefault(word, 0) + 1); } } // 输出结果 System.out.println("关键字\t\t出现次数"); for (Map.Entry<String, Integer> entry : keywordCounts.entrySet()) { System.out.printf("%-16s%d\n", entry.getKey(), entry.getValue()); } } private static boolean isKeyword(String word) { // Java关键字 String[] keywords = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"}; // 判断单词是否为关键字 return Arrays.binarySearch(keywords, word) >= 0; } } ``` 该程序先读取用户输入的源码,然后将源码转换为单词列表。接着,对于每个单词,判断是否为关键字,如果是则将其出现次数加一。最后,将统计结果按照关键字升序排序并输出。 需要注意的是,该程序只能统计出现在源码关键字,而无法统计在注释或字符串出现关键字

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值