Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# iterate through float values

Isaac Hewitt
Ranch Hand
Posts: 191
Hi

I am doing a sticky note program for myself and I have a JPopupMenu with a hide command in each note. I want to take advantage of the new translucency
in Java 6 Update N. The translucency method takes a float value so I need to iterate from 0.9f to 0.0f in a loop. I did it like so with an ArrayList of the values except I think this is a dumb way of doing it. The code runs smoothly and it give that exact desired effect. Is there any way to iterate through float values 9 to 0 without first adding those values to an ArrayList?

Thanks

Marco Ehrentreich
best scout
Bartender
Posts: 1294
Hi,

why not just use a for loop like this:

Marco

Isaac Hewitt
Ranch Hand
Posts: 191
Thanks so much Marco.

Marco Ehrentreich
best scout
Bartender
Posts: 1294
No problem

Unfortunately I don't know of a more elegant solution. Some Basic dialects had for loops where you could give a step width for this.

Perhaps you could refactor this code to a separate method which generates the sequence of values. But then you'd have to use an iterator or something with another loop. Don't know which one is better. Anyway I hope it's working...

Marco

Irina Goble
Ranch Hand
Posts: 91
What's the problem with a normal loop?

Marco Ehrentreich
best scout
Bartender
Posts: 1294
Oops, point for you, Irina :roll:

I don't know why the brain sometimes tries to find ideas that are more complicated than...

Paul Clapham
Sheriff
Posts: 20750
30
Originally posted by Irina Goble:
What's the problem with a normal loop?
The problem with that loop is that the values of f that it produces are these:

0.9
0.79999995
0.6999999
0.5999999
0.4999999
0.39999992
0.29999992
0.19999993
0.09999993

So it runs one time fewer than what you expected.

Irina Goble
Ranch Hand
Posts: 91
Originally posted by Paul Clapham:
So it runs one time fewer than what you expected.

Thank you, Paul. Tricky.
Using integers surely better, better precision and simple.
Atleast doubles will give all 10 steps, but then they have to be converted to float and 1.3877788E-16 is not quite a 0.0.

gives:
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
1.3877788E-16