I was given a homework in which I need to count the number of words in a file and output how many words are the same. Like "a" in the whole text maybe it was repeated 350 times. I hope you get my point.
Now, im trying to do some tests and created a file("test.txt") containing:
Im a good boy
Hello World
A happy world it is
What I'm trying to do is storing it into an array to be able to count the words in the file. But I'm having a hard time. This is what i got so far.
void readFile() {
System.out.println("Gi navnet til filen: ");
String filNavn = sc.next();
File k = new File(filNavn);
try {
Scanner sc2 = new Scanner(k);
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
String[] m = line.split(" ");
String x = m[0];
System.out.println(x);
}
} catch (FileNotFoundException e) {
System.out.print("mmm");
}
}
but this only outputs the first words on the line.
What I would like to see is the same as the text file. But stored in an array. How can I do it?
Im a good boy
Hello World
A happy world it is