Question: [JAVA] I keep getting this error ( Count the occurrences of words in a text file ) Rewrite Listing 21.9 to read the text from

[JAVA]

I keep getting this error

[JAVA] I keep getting this error (Count the occurrences of words in

(Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by whitespace characters, punctuation marks (, ; . : ?), quotation marks (' "), and parentheses. Count the words in a case-sensitive fashion (e.g., consider Good and good to be the same word). The words must start with a letter. Display the output of words in alphabetical order, with each word preceded by the number of times it occurs.

---------------------------------------------------------------- import java.io.File;

import java.util.Map;

import java.util.Scanner;

import java.util.Set;

import java.util.TreeMap;

public class CounterWordsFile {

public static void main(String[] args) {

String inputfilename = args[0];

TreeMap treeMap = new TreeMap

Integer>();

try {

Scanner input = new Scanner(new File(inputfilename));

while (input.hasNext()) {

String line = input.nextLine();

String[] words = line.split("[ @!~{}\\[\\]$#^&* \t .,;?'\") (]");

for (int i = 0; i

if (words[i].trim().length() > 0 && words[i].trim().matches("[AZ|az]+")) {

String key = words[i].toLowerCase();

if (treeMap.get(key) != null) {

int count = treeMap.get(key);

count++;

treeMap.put(key, count);

} else {

treeMap.put(key, 1);

}

}

}

}

} catch (Exception ex) {

ex.printStackTrace();

}

Set> entrySet = treeMap.entrySet();

System.out.print(" Total words in the file : ");

for (Map.Entry entry : entrySet)

System.out.println(entry.getValue() + "\t" + entry.getKey());

}

}

Select CAWINDOWSIsystem32\cmd.exe Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 Press any key to continue . at CounterWordsFile.main (CounterWordsFile.java:16)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!