我试图在这个简单中找到字符串all
,但我得到输出ho hum, i found 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);
}
}
答案 0 :(得分:1)
Add "lineNum++;" after the start of your while loop but before your if statement (unless you want the first line to be line 0, in which case increment after the if). You are never incrementing lineNum so it will stay 0.
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(line.contains("all")){
System.out.println("ho hum, i found it on line " +lineNum);
}