Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Word Counter Assignment Done #5

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions src/WordFrequency.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,70 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class WordFrequency {
public static void main(String[] args) {

System.out.println("Hello world!");
//scan in the file



Map<String, Integer> wordCounts = new TreeMap<>();

try {
Scanner infile = new Scanner(new File("tale.txt"));

while (infile.hasNext()){
String word = infile.next();
//check if word is in the map
if(wordCounts.containsKey(word)){

//get the existing value
int value = wordCounts.get(word);
//increment the count
value++;
//update/put the update value back in
wordCounts.put(word,value);
} else {
//add to the map
wordCounts.put(word,1);
}

}
} catch (FileNotFoundException e){
System.out.println("File not Found");
}




//write a loop to walk through (visit) items in the map print out each one
for (String key: wordCounts.keySet()){
int value = wordCounts.get(key);
System.out.println("word " + key + " appears " + value + " times ");
}


//Keep track of the max value of count
int maxValue = 0;
String maxString = "";
for (String key: wordCounts.keySet()){

int value = wordCounts.get(key);
if (value > maxValue){
maxValue = value;
maxString = key;
} else if (value == maxValue){
maxString += (", " + key);
}

}
System.out.println();
System.out.println();
System.out.println("Max Word(s): " + maxString);
System.out.println("Frequency: " + maxValue);
}
}