2014-02-10 18 views
1

當我運行程序時,它保持運行並且控制檯處於活動狀態以便輸入,所以我必須停止。這是爲什麼? (要在句子中找到鏡像詞。使用INTELIJ IDEA)。彙編繼續運行(模式,匹配器任務)

public class Blinov11 { 

    static String mirror(String str){ 
     String mirrored = ""; 
     for (int i = str.length() - 1; i >= 0; i--) { 
      mirrored += str.charAt(i); 
     } 
     return mirrored; 
    } 
    public static void main(String[] args) { 

     String text = new String("If the method atad fi takes data a sekat takes primitive data type as an argument, then the nhet String object representing the primitive data type value is return."); 
     Pattern pattern = Pattern.compile("\\W\\w+\\W",Pattern.CASE_INSENSITIVE); 
     Matcher matcher = pattern.matcher(text); 
     String word = ""; 
     while(matcher.find()){ 
      word = mirror(matcher.group()); 
      if(text.contains(word)){ 
       System.out.println(word); 
      } 
     matcher.reset(); 
     } 
    } 
} 

回答

3

也就是由於這樣的事實,我們在調用:

matcher.reset(); 

while loop內。按Java doc

public Matcher reset()

重置此匹配。 重置匹配器 會丟棄其所有顯式狀態信息,並將它的追加 位置設置爲零。匹配器的區域被設置爲默認區域 ,它是整個字符序列。該匹配器的區域邊界的錨定和透明度 不受影響。

因爲你while循環reset()的,匹配得到復位每次和while (matcher.find())成爲無限循環,因爲它總是從開始處找到。