| Author |
Closure Question
|
Brian Mooney
Greenhorn
Joined: Sep 30, 2010
Posts: 3
|
|
Hi,
Have been looking at Groovy recently and am interested in trying to learn it properly.
Was just trying some file manipulation using groovysh and I'm a little puzzled by something that I'm seeing.
I was simply trying to add line numbers to the contents of a file as per:
But when reviewing the output, I'm seeing:
1: 1st Line
2: 2nd Line
3: Some random text
4: Random Stuff
5: Last line
6: Well almost!!
If I update the code as per below (initialising the Integer i to 1 as opposed to 0):
I get the same output:
1: 1st Line
2: 2nd Line
3: Some random text
4: Random Stuff
5: Last line
6: Well almost!!
My question is why doesnt the first code block index the lines from zero?
To get the desired result, I have to edit the code as such:
which results in:
0: 1st Line
1: 2nd Line
2: Some random text
3: Random Stuff
4: Last line
5: Well almost!!
This is of course very trivial but I'm more wondering where my understanding of what is happening is falling down as I would have expected the final result to be produced by the very first code block.
Appreciate any correspondance
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 23635
|
|
Brian,
This does what you want. Passing the desired start index as a parameter prevents Groovy from using a default of 1 for the line number.
The eachLine method is defining the second argument to be the line number. It ignores any requests you make of i. For example, if you change i++ to i+=2, you get the same behavior 1-6 as before because eachLine is helpfully setting i to the line number for you.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Certs: SCEA Part 1, Part 2 & 3 & Core Spring 3, OCAJP
|
 |
Brian Mooney
Greenhorn
Joined: Sep 30, 2010
Posts: 3
|
|
Indeed you're right. I was getting confused about the inputs for the eachLine() method.
Appreciate the response and help on the matter.
Regards,
Brian
|
 |
 |
|
|
subject: Closure Question
|
|
|