This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 24183
    
  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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing odd and even list items of a String list in a single for loop
 
Similar Threads
Johnson Trotter Algorithm help
Adding list element to Object array
Iterating over Map using JSTL
Concatenate method result , repeat in each Request
iterator