This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get index in new for loop  RSS feed

 
Melinda Savoy
Ranch Hand
Posts: 387
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any help or direction would be greatly appreciated. How can I get the index in the following type of for loop:

 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The enhanced for loop is meant to iterate through the array or collection from beginning to end, so if you need to handle the array or collection in another way, I'd say you should use the old for loop.
Check out this page. Especially the paragraph at the very bottom.
[ June 26, 2007: Message edited by: Eric Daly ]
 
Melinda Savoy
Ranch Hand
Posts: 387
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eric,

Thanks for the reply. I"m not sure if there is a way to get at the index when I'm trying to loop through an object. I tried the following but I'm getting bad results:



Meaning I have one item that should be equal to 0 but because I've got the other loop that it is within then I"m getting 7 messages instead of 1. I guess I don't know how to account for "item" in the old for loop format.

Any help or direction would be appreciated. Thanks again.
[ June 26, 2007: Message edited by: Melinda Savoy ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer depends on what stockReq is and what its API looks like. Does it have any kind of get(int) method that lets you get a single item by index?

getReqItems() presumably returns an Iterator, so calling size() on it shouldn't work. The idea is to use a single old-style loop, not a double loop as you have here, retrieving the items with some kind of get(int) method. But if stockReq doesn't have such a method -- well, then you'd be stuck. So then what you'd have to do would look something like

 
Melinda Savoy
Ranch Hand
Posts: 387
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest,

Thank you so much. That was the ticket. I'm still having a hard time thinking out of the box. Though still trying. I appreciate the help of those on this list.

Thanks again!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!