I'm a beginner in Java. I just want to count the occurrences of every word from a text file. The input format is just like:
A B
A C
C A
B C
Here is what I have done so far:
public static void main (String[] args) throws FileNotFoundException
{
Scanner inputFile = new Scanner(new File("test.txt"));
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(line);
// above is the first part, to read the file in
// below is the second part, try to count
Map<String, Integer> counts = new HashMap<>();
for (String word : line) {
Integer count = counts.get(word);
counts.put(word, count == null ? 1 : count + 1);
}
System.out.println(counts);
}
}
The expect result would be like :
A 3
B 2
C 3
I got the first and second parts on google, but don't know how to combine those. Any suggestion would be helpful.