import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class WordCounter { // 2 fields for file name and hashmap private ArrayList<String> fn; private HashMap <String, Integer> hm; //private Scanner x; // constructor public WordCounter(String frame) { countwords(frame); } public ArrayList<String> getfn() { return fn; } public HashMap<String, Integer> gethm() { return hm; } // methods private void countwords (String fname) { try{ Scanner x = new Scanner (new File(fname)); while (x.hasNextLine()){ String[]words = x.nextLine().split("[^a]+"); for(String s: words) System.out.println(s); System.out.println(Collections.frequency(fn, hm)); }} catch (Exception e){ System.err.println(e); } } public void print() { System.out.println("Word:\t\tFrequency:"); System.out.println("===================================="); for(int i=0; i< fn.size(); i++){ System.out.println(); } } public static void main(String[] args) throws Exception { String fname = "test-file.txt"; if (args.length > 0) fname = args[0]; WordCounter wc = new WordCounter(fname); wc.print(); } }
Output
Word: Frequency:
====================================
java.lang.NullPointerException
Exception in thread "main" java.lang.NullPointerException
at WordCounter.print(WordCounter.java:46)
at WordCounter.main(WordCounter.java:59)