Code
/*Program to return the most common word in a text file using hashmap */
package com.ferfykins.exercises;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CommonWord {
public static void main(String[] args) {
String path = "/home/ferfykins273/Desktop/MyJavaCode/Exercises/SearchText/src/com/ferfykins/exercises/search.txt";
readFile(path);
}
public static void readFile(String path) {
Map<String, Integer> wordMap = new HashMap<>();
String line;
int initialValue = 1;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
while((line = br.readLine()) != null){
String[] data = line.split(" ");
for(String words : data) {
if(wordMap.containsKey(words)) {
wordMap.replace(words, initialValue+1);
initialValue++;
} else {
wordMap.put(words, initialValue);
}
}
}
System.out.println(searchItem + " was found " + wordCount + " times!!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
basically what i wanna do is use a hashmap, and put each word in the text file as a key, and the value would be the amount of times the word occurs.....
So what i wanna do is first check if the key exists, if it does exist, increment the value... and if the key does not exist yet, then add it as a key (each word in the text file)
Hopefully this make sense...... So i understand the logic behind it, but i'm not sure how to do it syntax wise... thanks guys.
This post was edited by ferf on Oct 2 2020 08:41pm