• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Closure Question

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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



 
author & internet detective
Posts: 40746
827
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Brian Mooney
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
reply
    Bookmark Topic Watch Topic
  • New Topic