You could also make a small class:
public class TrackWord{
String word;
int lineNumber;
int wordNumber;
}
Where word is the word itself, line number is the line the word was seen on, and word number of the word's position within that line. So for the sentence "I have a massive hangover" every word would have a line number of 1 and "massive" would have a word number of 4. You could easily implement this by doing the following:
int lineNumber = 1;
while(scanner.hasNextLine()){
String theLine = scanner.nextLine();
//theLine is now the next line from your file
Scanner lineScanner = new Scanner(theLine);
int wordCount = 0;
while(lineScanner.hasNext()){
String nextWord = lineScanner.next();
}
lineNumber++;
}
I intentionally left out some stuff from the above code (as per our homework rules), but that is the basic idea. To fully implement it, you'd have to increment wordCount in the appropriate place, and then you'd have to create a new TrackWord object, populate it with the name of the word and the line number and word number it was seen at, then add the TrackWords to an array.
P.S. Since you want to track
every line where 'fast' was seen, you could modify the class I showed above so that it had an ArrayList of line numbers. Then every time you saw the word fast, you could check to see if you already have a TrackWord Object for the word fast. And if you do, then you could add the line number you just saw it at to the TrackWord's ArrayList of line numbers. I hope that made sense.
P.P.S not trying to step on your toes JavaAddict, your solution works, this seems simpler to me though. And congrats on your 1500th post