I am trying to display all words in a file that can be found horizontally and vertically and I am trying print the location of the first character of each word (row and column).
I got it to display every word horizontally but not vertically.
This is the code I used so far
public class WordFinder {
public static final String WORD_FILE = "words.txt";
public static void find(){
try {
File file = new File(WORD_FILE);
Scanner scanner = new Scanner(file);
while (scanner.hasNext() == true) {
String s = scanner.next();
System.out.println(s);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
It should search the file horizontally and vertically to find words. Once it finds a word it should display the location of the first letter of the word (E.G. grammar: row 8, position 1
) At the moment it just prints all horizontal words.
You have to count the line number and position of the words while iterating. Therefore you should use scanner.hasNextLine()
and scanner.nextLine()
. After that you can split the line:
int lineNumber = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
int positionNumber = 0;
for (String word : line.split("\\s")) {
if (!word.isEmpty())
System.out.println(word + ": line " + (lineNumber + 1) + ", position " + (positionNumber + 1));
positionNumber += word.length() + 1;
}
lineNumber++;
}
This splits the line on all whitespaces (\\s
) and handle double whitespaces (empty words) with if (!word.isEmpty())
.