计算数组中每个元素出现在文件中的次数

时间:2017-04-03 12:30:53

标签: java arrays java.util.scanner java-io

我写了下面的代码来回答上面的问题。谁能告诉我哪里出错了?

我希望看到代码返回数组中每个元素在文本文件中出现的确切次数。无论空格,制表符,换行符等。

public class counter {
    public static void main(String[] args) throws FileNotFoundException  {
        String[] wordname;
        wordname = new String[] {"harry","ron","george","fred"};
        File file = new File("file.txt");
        Scanner scanner = new Scanner(file);
        for(int i=0; i < wordname.length; i++){
            scanner.useDelimiter(wordname[i]);
            int occurences = 0;
            while(scanner.hasNext()){
                scanner.next();
                occurences++;

            }
            System.out.println(wordname[i] + ": " + occurences);
        }
        scanner.close();

    }
}

输出:
哈里:6 郎:1
乔治:0
弗雷德:0

文件:
    哈利哈里罗恩乔治哈里哈里     harry harry har
ron ron ron ron fred     弗雷德弗雷德乔治     哈里

2 个答案:

答案 0 :(得分:0)

  

你应该使用空格而不是单词和你的代码扫描文件进行多次分割,这也会降低性能。

     

因此以这种方式执行相同的任务是很好的:

public class Counter {
public static void main(String[] args) throws FileNotFoundException {
    String[] wordname;
    wordname = new String[]{"harry", "ron", "george", "fred"};
    Map<String, Integer> map = new HashMap<>();
    for (String string : wordname) {
        map.put(string, 0);
    }
    File file = new File("file.txt");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter("\\s+");
    String word;
    while (scanner.hasNext()) {
        word = scanner.next();
        if (map.containsKey(word)) {
            map.put(word, map.get(word) + 1);
        }
    }

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
}
}

答案 1 :(得分:0)

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Example {
    public static void main(String[] args) throws FileNotFoundException {
        //read whole file to string only once
        String fileContent = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
        String[] wordname = {"harry","ron","george","fred"};
        // filter each name and count occurrences
        for (String name : wordname){
            long count = Arrays.stream(fileContent.split(" ")).filter(s -> s.equals(name)).count();
            System.out.println(name + " : " + count);
        } 
    }
}