Created
June 19, 2014 23:15
-
-
Save keshavsaharia/d194129274dc55f0ac91 to your computer and use it in GitHub Desktop.
wordfreq
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
package PhotoEditor; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.util.HashMap; | |
import java.util.Scanner; | |
public class HashMapFun { | |
public static void main(String[] args) { | |
HashMap <String, Integer> wordFrequency = new HashMap <String, Integer> (); | |
String bookContent = getFile("book"); | |
String[] words = bookContent.split(" "); | |
// Go to every word in the list | |
for (String word : words) { | |
// If I've already added this word to the frequency map | |
if (wordFrequency.containsKey(word)) { | |
int number = wordFrequency.get(word); | |
number = number + 1; | |
wordFrequency.put(word, number); | |
} | |
// I haven't yet seen the word | |
else { | |
wordFrequency.put(word, 1); | |
} | |
} | |
} | |
public static String getFile(String path) { | |
// Make a File object to represent this file at the path | |
File f = new File(path); | |
// Do the code in the try, and if it fails do the catch code | |
try { | |
// Make a scanner to read the file | |
Scanner fileScanner = new Scanner(f); | |
// Make a StringBuilder to create the file content | |
StringBuilder content = new StringBuilder(); | |
// While the file scanner still has a line of input | |
while (fileScanner.hasNextLine()) { | |
// Append the next line of file input | |
content.append(fileScanner.nextLine()); | |
// Append a newline character. | |
content.append("\n"); | |
} | |
// Return whatever is in the StringBuilder | |
return content.toString(); | |
} | |
// Catch any error that may occur in the above try statement | |
catch (FileNotFoundException e) { | |
System.out.println("Didn't find the file."); | |
} | |
return ""; // If all else fails, return an empty string. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment