[JAVA] Please find error. This isn\'t working. ---------------------------------
ID: 3725896 • Letter: #
Question
[JAVA]
Please find error. This isn't working.
----------------------------------------------------------------------------------------------
import java.io.*;
import java.util.*;
public class CountWordsFile {
@SuppressWarnings("resource")
public static void main(String[] args){
String javaprogramming = args[0];
TreeMap<String,Integer>TreeMap=new TreeMap<String,Integer>();
try{
Scanner input = new Scanner(new File("testing.txt"));
while (input.hasNext()){
String line=input.nextLine();
String[]words=line.split("[ @!~{}\[\]$#^&* .,;?'")(] ");
for (int i=0;i<words.length;i++){
if (words[i].trim().length () >0 && words[i].trim().matches("[A-Z|a-z]+")){
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<Map.Entry<String,Integer>>entrySet=TreeMap.entrySet();
System.out.print(" Total words in the file:");
for (Map.Entry<String, Integer>entry: entrySet) System.out.println(entry.getValue()+" " +entry.getKey());
}
}
Explanation / Answer
Hi
I have fixed the issue and highlighted the code changes below
CountWordsFile.java
import java.util.*;
public class CountWordsFile {
public static void main(String[] args){
String fileName = args[0];
TreeMap<String,Integer> treeMap=new TreeMap<String,Integer>();
int wordCount = 0;
try{
Scanner input = new Scanner(new File(fileName));
while (input.hasNextLine()){
String line=input.nextLine();
String[]words=line.split("\s+|(?=\p{Punct})|(?<=\p{Punct})");
wordCount = wordCount+words.length;
for (int i=0;i<words.length;i++){
if (words[i].trim().length () >0 && words[i].trim().matches("[A-Z|a-z]+")){
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<Map.Entry<String,Integer>>entrySet=treeMap.entrySet();
System.out.println(" Total words in the file: "+wordCount);
for (Map.Entry<String, Integer>entry: entrySet) {
System.out.println(entry.getValue()+" " +entry.getKey());
}
}
}
Output:
Total words in the file: 42
2 a
1 after
2 and
1 annoying
1 awful
1 bad
1 everyone
1 happy
2 he
1 ice
1 liked
1 nobody
1 on
1 once
1 one
1 pop
1 sang
1 slipped
1 smelled
1 some
1 the
1 there
1 told
1 upon
1 very
2 was
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.