0

I am trying to read a text file and to process it word by word using data structures of Singlylinkedlist, doublylinkedlist, and ArrayList. but when I call the method processword it refuses to continue after reading the first word. if the word is in one of the lists it will increment how many times a word is mentioned.

I tried changing the loops and the if statement but none of it worked

}

    public void processText(String filename) {

    File file = new File(filename);
    String r;
    try {
        Scanner sc = new Scanner(file);
        sc.useDelimiter("\\s+|\\d+\\ ");

        while (sc.hasNextLine()) {
            count = count + 1;
            System.out.println(count);
            r = sc.next();
            String l = r.toLowerCase();
            System.out.println(l);
            processWord(l);
        }
        sc.close();
    } catch (Exception ex) {
        System.out.println(ex);
    }

}

/* This method will insert a new word in the
 list or increment the frequency count of the word
 if it is already in the list... 
 */
public void processWord(String word) {
    SinglyLinkedList<String> Slist = new SinglyLinkedList<>();
    DoublyLinkedList<String> Dlist = new DoublyLinkedList<>();
    ArrayList<String> Alist = new ArrayList<>(count);

//Contains is a method that checks if word is in the list or not returns boolean

    if (Slist.Contains(word) != true) {
        Slist.insert(word);
        Dlist.insert(word);
        Alist.insert(word);
    } else {
        String[] ar = null ;
        Map<String, Integer> mp = new HashMap<>();
        int WordCount = 0;

        for (int i = 0; i < ar.length; i++) {
            WordCount = 0;

            for (int j = 0; j < ar.length; j++) {
                if (ar[i].equals(word)) {
                    WordCount++;
                }
            }
            mp.put(ar[i], WordCount);
        }
        System.out.println(mp);
    }
}

1

before

java.lang.NullPointerException

this is what I get when I run the program

1 Answers1

0

You are initializing ar variable as null and then try to access the length property of it, which is giving your error. Further info of what null is here: What is null in Java?

Furthermore, what is ar supposed to be in the first place? As a tip, try to name variables as a semantic reflection of their meaning in your code. It'll help you a ton when going over the code later and trying to figure out what you meant

Calin Oana
  • 23
  • 4