java - 在文本文档行中查找字符串

标签 java

我试图在这个简单的文件中找到字符串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/

相关文章:

java - Jna链接错误: How to solve this error while starting cassandra

java - 确定 Java 中 TLS 握手的 Diffie-Hellman "Parameters"长度

java - 在 Vert.x Web 路由器上的不存在路由上提供静态 webroot/index.html 数据

java - 如何在每个用户 firebase android 中创建唯一的 token ?

java - 如何在集群上使用 JVM 程序? (比如停产的 cJVM/JavaSplit)

java - 为什么 Hibernate 不填充这个外键列

java - CQRS 和 EventSourcing 的框架建议

java - 将 MouseAdapter 列表的所有元素添加到 JComponent

java - 为什么启用断言时 java 代码覆盖率仍然显示黄色

java - 通过Java查找嵌套组中的LDAP用户