permaculture playing cards*
The moose likes Beginning Java and the fly likes enhanced 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 "enhanced for loop" Watch "enhanced for loop" New topic
Author

enhanced for loop

Emily Vieille
Greenhorn

Joined: Nov 27, 2006
Posts: 5
how would you alternately add and then subtract individual elements of the array of the enhanced for loop from an accumulator? I'm not really sure how to seperate them... so far I have:


so for example how would you add 1 then subtract 4 add 9, etc? I'm not sure if that's right...
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

Use the modulus operator:

x % 2

If the remainder is zero, you know that you have an even number. If the remainder is one, then you know that you have an odd number.

Then you use the if and the else keywords to either add or subtract.

You don't want to add or subtract x. You want to add or subtract the elements of the array which would be:

data[x]

-- Kaydell
[ December 05, 2006: Message edited by: Kaydell Leavitt ]
Emily Vieille
Greenhorn

Joined: Nov 27, 2006
Posts: 5
thanks but they're not only even/odd every other one
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
I would respectfully disagree with some of what Kaydell said.

The variable x in the enhanced for loop is the element of the array, not the subscript.

In order to do what you want to do, you would need to use the other variable count that you have and increment it in your loop, then you could use the modulus operator on count.

I think it might be easier in accomplishing your goal to use a regular for loop.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

I agree with Keith. x is not the loop counter, as Keith said, it is the element of the array. I'm not used to the for-each loop. I agree with Keith too that using a regular for loop is best because then you have access to the variable that counts the iterations of the loop.

-- Kaydell
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14116
    
  16

When you use the new for loop syntax, you don't have access to the loop index. So you can't see if the index is even or odd.

You could do it simply with a boolean flag that you flip in each iteration of the loop:

or, with a more compact syntax:

[ December 06, 2006: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Emily Vieille
Greenhorn

Joined: Nov 27, 2006
Posts: 5
ok thanks everyone for the help!
 
Don't get me started about those stupid light bulbs.
 
subject: enhanced for loop