猿问

Java扫描仪从文件中读取字符频率

我正在尝试让扫描仪在使用扫描仪时读取文件路径中字符的频率。我应该添加什么来完成此方法以执行我所描述的操作。使用优先级队列。


public static Huffman build(String filePath) throws IOException {

    if (filePath == null) {

        throw new NullPointerException("File doesn't exist");

    } else {

        try {

            Scanner file = new Scanner(new File(filePath));

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        }

        while (file.hasNextLine()) {

            Scanner s2 = new Scanner(file.nextLine());

            while (s2.hasNext()) {

                String s = s2.next();

                System.out.println(s);

            }

        }

    }

}


陪伴而非守候
浏览 115回答 3
3回答

回首忆惘然

优先级队列相对简单,它是一个保留顺序的堆。虽然 hashmap 在这里可能会更好,但 pqueue 并不可怕。只需遍历文件的整个字符数组。将所有内容放入优先队列。要获得频率,只需弹出 pqueue 并将其存储在地图或类似的东西中,或者将其输出到任何需要输出的地方。Map 好多了,但是如果你必须使用优先级队列,那就相对简单了

拉风的咖菲猫

我建议使用简单的映射而不是优先级队列。使用Files.lines()和 Java Stream 你可以使用这个:public static Map<String, Long> build(String filePath) throws IOException {&nbsp; &nbsp; if (filePath == null) {&nbsp; &nbsp; &nbsp; &nbsp; throw new NullPointerException("File doesn't exist");&nbsp; &nbsp; }&nbsp; &nbsp; try (Stream<String> lines = Files.lines(Paths.get(filePath))) {&nbsp; &nbsp; &nbsp; &nbsp; return lines.map(s -> s.split("")).flatMap(Arrays::stream)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));&nbsp; &nbsp; }}如果您需要字符的顺序,您可以使用 a LinkedHashMap,它保持插入顺序。将我上面示例的收集器更改为:Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())

Qyouu

好吧,如果您不想使用 HasMap 或 PriorityQueue,这是一个替代解决方案,您可以使用一个简单的整数频率数组来存储编号。所有字母的出现。我使用了大小为 128 的整数数组来涵盖所有类型的字符,包括大写、小写、特殊字符或数字。(您可以在将用户输入存储到 String 之后立即添加这段代码)&nbsp; &nbsp; int[] count = new int[128]; // initially they all will be zero&nbsp; &nbsp; for(char ch:s.toCharArray()){&nbsp; &nbsp; &nbsp; &nbsp; count[ch]++;&nbsp; &nbsp; }&nbsp; &nbsp; for(int i=0;i<128;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(count[i]!=0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println((char)i+":"+count[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答