[英]Get all words from text file (Java)
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 (EG grammar: row 8, position 1
) At the moment it just prints all horizontal words.一旦找到一个单词,它应该显示单词的第一个字母的位置(EG grammar: row 8, position 1
)目前它只打印所有水平单词。
You have to count the line number and position of the words while iterating.您必须在迭代时计算单词的行号和位置。 Therefore you should use scanner.hasNextLine()
and scanner.nextLine()
.因此,您应该使用scanner.hasNextLine()
和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())
.这将在所有空格 ( \\\\s
) 上拆分行并使用if (!word.isEmpty())
处理双空格(空词if (!word.isEmpty())
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.