programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# enhanced for loop

Greenhorn
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...

Ranch Hand
Posts: 693
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
Posts: 5
thanks but they're not only even/odd every other one

Ranch Hand
Posts: 2410
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
Posts: 693
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

Java Cowboy
Sheriff
Posts: 16079
88
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 ]

Emily Vieille
Greenhorn
Posts: 5
ok thanks everyone for the help!

 I yam what I yam and that's all that I yam - the great philosopher Popeye. Tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS