Ask a Question

How to use "break in the following loop?

indraniria
Contributor

How to use "break in the following loop?

for(File file: f.listFiles())
{
if (file.getName().contains(date_time) ||file.getName().contains(next_day)){
file.eachLine{line ->
if(line.contains(text)){
log.info file.getName()

break
}
}
}

 

Getting below error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 23: the break statement is only allowed inside loops or switches
@ line 23, column 5.
break
^
}

1 REPLY 1
ChrisAdams
Community Leader

Hi,

Don't use for-each loop.  Instead, use a 'traditional' for loop or while loop.  I've wrote a second version in your other recent question to stop at the first instance of the string being found.  That includes a for loop with a break statement.

I cheated slightly in the other solution by reading the contents of the entire file into a single string.

In your example above, you would need two break statements, one for each loop.  You might find it easier and more readable to split into functions.

 

 

 

cancel
Showing results for 
Search instead for 
Did you mean: