Reputation: 3557
One of my homework assignments was to write a small enhanced for-loop with floats. I understand the basis of this loop style with integer arrays, to my understanding:
for (int i = 0; i < some.number; i++)
is equivalent to
for (int i : array_example)
If this is accurate how is this supposed to work with a array filled with floats? I thought the incremental operator (i++
) was only allowable with integers. Just looking for some clarification.
Thanks.
EDIT: Here's an example of what I'm doing, and what Eclipse doesn't like. Which is probably adding to my confusion:
public class java_array
{
public static void main(String[] args)
{
float[] values = {1/2,1/3,5/3};
float total = 0;
for (float i : values)
{
values[i] = i; //Getting an error here "can't convert from float to int.
}
for (float i : values)
{
System.out.println(values[i]); //Getting an error here "can't convert from float to int.
}
}
}
Everything has been declared as float
. Why is the IDE saying this?
Upvotes: 1
Views: 5849
Reputation: 13610
The two for loops aren't exactly equivalent. The first for loop is in fact mostly similar to a while loop.
for(init; condition; post) {
... code
}
Is similar to:
init;
while(condition) {
... code
post;
}
If you go deeper, you'll realize that most syntax can be rewritten using gotos. It's just syntastic sugar to make it "less" prone to errors.
The other form is using an iterator. This for form is able to get an iterator from an object such as arrays. The can be implemented on other objects. That said, there is 2 problems in your code.
for (float i : values)
{
values[i] = i; //Getting an error here "can't convert from float to int.
}
When you're iterating over values, you cannot set values[i]
to something because i
is of type float. Indexes for arrays are usualy ints, because you cannot access an object in between two objects.
The second less obvious problem is that you're changing the value of values within a for loop. There are chances that the code above will work but you have to understand that an iterator isn't simply a way to iterate over objects in a list.
As far as I remember, if you had some kind of concurency. Editing the values pointed by an iterator might invalidate the iterator. It will raise an exception because you could be iterating over invalid data. The iterator pattern usually force to raise an exception and restart the for loop if possible. If you change the data within the for loop it could raise such kind of exception.
Upvotes: 2
Reputation: 2483
The enhanced for-loop is "syntactic sugar" for a standard for-loop. You can read more about the enhanced for-loop here: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with
The following would work (assuming values is a float array):
for (float value : values)
{
// value contains the iteration's float value. e.g.
System.out.println(value);
}
When using the enhanced for-loop, there is no need to use an index to iterate through the items in the array.
Upvotes: 3
Reputation: 209092
for (int i : array_example)
Reads like this. For each int
in int array array_example
, do something with that int
. the i
is just a random variable you use to access
that int
. i
can be any variable. You can call it turkey
if you want.
int[] array_example = {1, 2, 3};
for (int turkey : array_example){ // for each int in array_example
System.out.print(turkey + ", "); // print out that int
}
output: 1, 2, 3
For float
float[] floatArray = {1.2, 2.3, 3.4};
for (float watermelon : floatArray){
System.out.print(watermelon + ", ");
}
output: 1.2, 2.3, 3.4
Edit: after OP edit
You just need System.out.println(i);
. The other error is because you're trying to use the float i
as an index. an index needs to be an int
.
Upvotes: 1
Reputation: 13344
You can apply enhanced for-each
loop to any array or any object that implements Iterable
interface.
It is a short-cut for a loop with Iterator
Java Collections
satisfy the criteria and can be used with for-each loops.
In your particular case (array of floats) you will have something like this:
float[] fArray = {1f, 2f, 3f, 4f, 23F, 24F};
for (float element: fArray) {
System.out.println(element);
}
Please note that element
is a copy of an actual array element and if you assign a value to it directly, it will have no impact on the array itself.
Upvotes: 1
Reputation:
The type changes
for (float i : array_example)
underneath an iterator has an index which count to integer and has that type.
in the EDIT code values[i]
is erroneous because i
is float an can't be an index. IDE is your choice it complains before the compilation time because it is capable to catch errors like that. You should trust it.
Upvotes: 1
Reputation: 15729
The enhanced for loop, returns the values in the array, not the indices.
In the integer case, if myArray = [2,4,6,8];
for (int i : myArray)
// returns 2,4,6,8, NOT 0,1,2,3
In a traditional loop, you have an extra step
for (int idx = 0; idx<myArray.length; i++) {
// idx will be 0,1,2,3
int value = myArray[i]; <<< in many cases this is an extra step
// value will be 2,4,6,8
}
Now, if you need both the index and the value for some reason, you need the old fashioned loop.
So, for an old fashioned loop over a floatArray, you need an int for the index and a float for the value. If floatArray = [2.2, 4.4, 6.6, 8.8]
for (int idx = 0; idx<floatArray .length; i++) {
// idx will be 0,1,2,3
float value = floatArray [i];
// value will be 2.2, 4.4, 6.6, 8.8
}
with the enhanced for loop, you just need a float
for (float value : floatArray ) {
// value will be 2.2, 4.4, 6.6, 8.8
Upvotes: 4
Reputation: 3822
The for loop contains three parts:
i++
Your second for loop is actually a foreach. What it does is, it iterates through all Elements in the array and return them to you. The objects inside your array don't matter, it can be int, float, Object, whatever.
For example:
Object [] objects = new Object[100];
for (Object o : objects) {
// will go through all 100 elements, returning them one after the other as o
}
float [] floats = new float[100];
for (float f : floats) {
// will go through all 100 elements as well, returning them as f
}
Upvotes: 2