Created
August 25, 2018 04:10
-
-
Save rr-codes/fdf9dba8e98018a317adc1c7bcf4d169 to your computer and use it in GitHub Desktop.
The Frequency program outputs the frequency of each word in input file sorted alphabetically, and outputs the word with greatest frequency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* The Frequency program outputs the frequency of each word in input | |
* file sorted alphabetically, and outputs the word with greatest frequency | |
*/ | |
import java.io.*; | |
import java.util.*; | |
public class Frequency { | |
public static void main(String[] args) throws Exception { | |
Scanner fileName = new Scanner(System.in); | |
System.out.print("Please enter the name of the input file: "); | |
Scanner inputFile = new Scanner(new File(fileName.nextLine())); | |
fileName.close(); | |
String maxKey = null; | |
int maxFreq = 0; | |
TreeMap<String, Integer> map = new TreeMap<>(); | |
while (inputFile.hasNext()) { | |
String word = inputFile.next(); | |
Integer count = map.get(word); | |
map.put(word, (count == null) ? 1 : count + 1); | |
} | |
inputFile.close(); | |
for (String key : map.keySet()) { | |
int freq = map.get(key); | |
System.out.println("Word: " + key + ", Frequency: " + freq); | |
if (freq > maxFreq) { | |
maxFreq = freq; | |
maxKey = key; | |
} | |
} | |
System.out.println("\nMaximum: " + maxKey + ", " + maxFreq); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment