【问题标题】:while(Matcher.find()) is looping infinitelywhile(Matcher.find()) 无限循环
【发布时间】:2011-09-26 03:48:32
【问题描述】:

我从Oracle's Java Tutorials修改了以下代码:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTestHarness {

public static void main(String[] args){

    while (true) {
        Pattern pattern = Pattern.compile("foo");
        Matcher matcher = pattern.matcher("foo foo foo");

        boolean found = false;
        while (matcher.find()) {
            System.out.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end());
            found = true;
        }
        if(!found){
            System.out.format("No match found.%n");
        }
    }
}
}

我正在尝试学习如何在 Java 中使用正则表达式。 (我对正则表达式非常有信心,只是对使用它们的 Java 类没有信心。)我正在使用 Eclipse,我对它也不是非常熟悉。我不知道如何让控制台不被初始化为 null(正如教程警告的那样),所以我删除了它,只是使用静态值并在每次我想尝试新的东西时重新编译。

当我运行这段代码时,我得到一个无限循环:

I found the text "foo" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 4 and ending at index 7.
I found the text "foo" starting at index 8 and ending at index 11.
I found the text "foo" starting at index 0 and ending at index 3.

等等,等等,直到我点击终止

我做错了什么?

谢谢。

没关系... >.

【问题讨论】:

  • 请将对您最有帮助的答案标记为您接受的答案,而不是要求删除该问题。它可能会使其他初学者受益。

标签: java regex eclipse loops


【解决方案1】:

while(true){...} 被称为无限循环。停止执行此类循环的唯一方法是插入break,否则您将卡在该代码块中

【讨论】:

  • 在某些时候电源或硬件组件会出现故障,所以这不是 thaaaaaat 坏...
【解决方案2】:

您的 while 循环中没有终止条件。

链接页面上的练习描述还指出程序确实会重复循环。

【讨论】:

    【解决方案3】:

    外部while(true) 循环仅用于演示目的,以便它可以不断询问您的输入。你不需要一直要求输入;所以应该删除while(true) 循环。

    【讨论】:

      【解决方案4】:

      while(true)永远不会终止!

      【讨论】:

      • +/-1,你的声音里有太多的怀疑。 :)
      【解决方案5】:

      您当前在代码的该部分周围有一个while(true)while(true) 是一个无限循环,你似乎永远无法摆脱它。

      【讨论】:

        猜你喜欢
        • 2015-06-25
        • 2014-03-29
        • 2016-08-27
        • 2015-04-29
        • 2014-05-30
        • 2017-10-12
        • 2020-11-30
        • 2015-05-22
        • 1970-01-01
        相关资源
        最近更新 更多