For enhanced loop

• January 2nd, 2013, 07:45 PM
maple1100
For enhanced loop
Do the enhanced loop work with double? I get a loss of precision in the for loop at "double count". What can I change to make it work or do I just have to use for loop instead of enhanced? Thanks

Code :

``` double []x1 = new double[21]; double increment = 0.1; double start = 1.00; for(double count:x1) { x1[count] = (start - increment); start = x1[count]; }```
• January 2nd, 2013, 08:00 PM
Norm
Re: For enhanced loop
Why are you using a double for an index to an array? That makes no sense.

--- Update ---

Quote:

string can be used for an index to an array
Can you post an example of that? I've always used only ints for array indexes.

Quote:

Do the enhanced loop work with double?
Yes an enhanced loop will work with double (or any data type)
The problem with the posted code is the array indexing.
• January 2nd, 2013, 08:02 PM
maple1100
Re: For enhanced loop
I believes this is using the string as indexes right? Or I might be wrong.
Code :

```String[] names = { "fred", "jane", "eric" };   for ( String name : names ) { System.out.println( name ); }```
• January 2nd, 2013, 08:06 PM
Norm
Re: For enhanced loop
You said:
Quote:

string can be used for an index to an array
Can you post an example where a String is used as an index to an array? The code in post #3 does not use a String as an index. The code would look like this:
Code :

`anArray["a String"]`
• January 2nd, 2013, 08:10 PM
maple1100
Re: For enhanced loop
Oh, I'm sorry. I though indexes of the array was referring to what is used to define the index of the array inside the for loop. For indexes to an array, they can only be int right?
• January 2nd, 2013, 08:11 PM
Norm
Re: For enhanced loop
Yes
• January 2nd, 2013, 08:19 PM
maple1100
Re: For enhanced loop
Could you give me a hint on how to make the double work with for enhanced loop? Do I have to declare an "int" inside the loop and used that as the indexes or perhaps casting? I try both but none give me a double back but an int instead.
• January 2nd, 2013, 08:24 PM
Norm
Re: For enhanced loop
Quote:

how to make the double work with for enhanced loop?
The enhanced loop in post#1 works.
The problem is using a double to index an array. Array indexes should be int. If you must use a double you need to convert it to an int. What int value should 2.9 be converted to? 2 or 3
• January 2nd, 2013, 08:30 PM
maple1100
Re: For enhanced loop
2.9 to int would be "2". So if I wanted to used int for the double array, do I need to declare a new int inside the loop that can be used to index the array ? Thanks
• January 2nd, 2013, 08:34 PM
Norm
Re: For enhanced loop
If 2.9 is to be used as 2, you could cast the double to an int.