我试图在这个简单的文件中找到字符串all
,但我得到了输出ho hum, i find it on line 0
我该如何解决这个问题?
感谢任何帮助。
简单:
apple 05:09 05:39 06:11 06:41 07:11 07:41 08:11 all 17:11 17:41 18:11 18:41 19:11 19:41
chair 05:11 05:41 06:14 06:44 07:14 07:44 08:14 30 17:14 17:44 18:14 18:44 19:14 19:44
table 05:13 05:43 06:17 06:47 07:17 07:47 08:17 Min 17:17 17:47 18:17 18:47 19:17 19:47
代码:
try (PrintWriter writer = new PrintWriter(path + File.separator
+ newName);
Scanner scanner = new Scanner(file)) {
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("all")){
System.out.println("ho hum, i found it on line " +lineNum);
}
}
最佳答案
添加“lineNum++;”在 while 循环开始之后但在 if 语句之前(除非您希望第一行是第 0 行,在这种情况下在 if 之后递增)。您永远不会增加 lineNum,因此它将保持 0。
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(line.contains("all")){
System.out.println("ho hum, i found it on line " +lineNum);
}
关于java - 在文本文档行中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670433/