如何在java中循环外部访问局部变量

时间:2014-07-04 07:53:21

标签: java

我有一个txt文件,而一行是这样的:

"Execution Status: Pass"

我想取出价值:从这里传递。

我正在使用以下代码:

String patternString1 = "(Execution) (Status:) (.*)";
Pattern patt1 = Pattern.compile( patternString1 );
BufferedReader r = new BufferedReader(new  FileReader( "c:\\abc.txt" ));
String line;
while ( (line = r.readLine()) != null ) {
    String g11 = null; 
    Matcher m1 = patt1.matcher( line );
    while ( m1.find() ) {
        g11=m1.group(3);
        System.out.println(g11+"HI1"); //Line1
    }
    System.out.println(g11+"HI1"); //Line2
}

当第1行给出所需的输出时,#34;传递"我没有得到第2行的预期输出。 你们中的任何一个人都可以帮助我在循环中访问局部变量吗?

4 个答案:

答案 0 :(得分:0)

您可以尝试更改以下行:

while (m1.find())

 if(m1.find())

它应该给出你想要的结果

答案 1 :(得分:0)

简单方法怎么样:

String result = line.replaceAll(".*: ", "");

这一行说“将所有内容替换为冒号空间”(即删除它)。

答案 2 :(得分:0)

如果单行中只有一个匹配实例,则在找到匹配后使用if代替while (m1.find())循环或break循环。

示例代码:

while ( (line = r.readLine()) != null ) {
    String g11 = null; 
    Matcher m1 = patt1.matcher( line );
    if( m1.find() ) {
        g11=m1.group(3);            
    }
    if(g11 != null){
        System.out.println(g11+"HI1"); //Line2
    }
}

答案 3 :(得分:0)

在方法的开头将String g11声明为局部变量

 String g11="";   -- declare g11 as a local variable
  String patternString1 = "(Execution) (Status:) (.*)";
  Pattern patt1 = Pattern.compile(patternString1);

Add the rest of your code here.........