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

Java扫描器从文件中读取字符频率,java,algorithm,hashmap,huffman-code,Java,Algorithm,Hashmap,Huffman Code,我试图让扫描仪在使用扫描仪时读取文件路径中字符的频率。我应该添加什么来完成此方法以完成我所描述的。使用优先级队列 public static Huffman build(String filePath) throws IOException { if (filePath == null) { throw new NullPointerException("File doesn't exist"); } else { try {

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

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);
            }
        }
    }
}

优先级队列相对简单,它是一个保持顺序的堆。虽然hashmap在这里可能更好,但pqueue并不可怕

只需浏览文件的整个字符数组。把所有东西都放在优先队列中。要获得频率,只需弹出PQUE并将其存储在地图或类似的东西中,或者将其输出到需要输出的任何地方


Map要好得多,但如果您必须使用优先级队列,它相对简单

我建议使用简单的Map而不是优先级队列。使用
Files.lines()
和Java Stream,您可以使用:

public static Map<String, Long> build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    }
    try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
        return lines.map(s -> s.split("")).flatMap(Arrays::stream)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}

如果您不想使用HasMap或PriorityQueue,这是另一种解决方案,您可以使用一个简单的整数频率数组来存储所有字母的出现次数。我使用了大小为128的整数数组来覆盖所有类型的字符,包括大写、小写、特殊字符或数字。(您可以在将用户输入存储到字符串s后立即添加此代码段)

int[]count=new int[128];//最初它们都是零
for(char ch:s.toCharArray()){
计数[ch]++;
}
对于(int i=0;i
Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())
    int[] count = new int[128]; // initially they all will be zero
    for(char ch:s.toCharArray()){
        count[ch]++;
    }
    for(int i=0;i<128;i++){
        if(count[i]!=0){
            System.out.println((char)i+":"+count[i]);
        }
    }