aspose file tools*
The moose likes Beginning Java and the fly likes Accessing odd and even list items of a String list in a single for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing odd and even list items of a String list in a single for loop" Watch "Accessing odd and even list items of a String list in a single for loop" New topic
Author

Accessing odd and even list items of a String list in a single for loop

sony vijay
Ranch Hand

Joined: Jun 27, 2010
Posts: 32
Hi,

Say I have a String List like so:



I am trying to access all even elements and odd elements in the same for loop like so:



This code is obviously wrong because doing an i+1 while trying to access odd elements, increases the value of i which leads to wrong result by the time I try to access the next even element. I understand that my code is wrong but I was just trying to show what is it that I am seeking to do. Could someone tell me what is the right way to do this?

Thanks,
Sony
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

Instead of using i++ to increment the index by one, you just need to increment it by two. Make sense? I'll let you figure out the little bit of code yourself, but just replacing that i++ is going to do it.


[Jess in Action][AskingGoodQuestions]
sony vijay
Ranch Hand

Joined: Jun 27, 2010
Posts: 32
I got it. Thanks
 
 
subject: Accessing odd and even list items of a String list in a single for loop