I need to count number of occurences of the same strings in txt file.
What I have come up with is
public class CountWords {
public File file;
public Scanner scan = null;
public LinkedHashMap<String, Integer> list = new LinkedHashMap<>();
public CountWords(String txt) {
file = new File(txt);
}
public void textEdit() {
try {
scan = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("----");
}
while (scan.hasNextLine()) {
String line = scan.nextLine();
if(!list.containsKey(line))
list.put(scan.next(),1);
else {
list.put(line,list.get(line)+1);
}
}
scan.close();
}
public List<String> getResult(){
textEdit();
return list;
}
the class Main shouldn't be changed in any way (that is the requirement) and the output should be in the same order as input (that's why LinkedHashMap is used)
public class Main {
public static void main(String[] args) throws Exception {
String fname = System.getProperty("user.home") + "/textforwords.txt";
CountWords cw = new CountWords(fname);
List<String> result = cw.getResult();
for (String wordRes : result) {
System.out.println(wordRes);
}
}
}
I missed something that I can't figure out.