This book is now obsolete Please use CSAwesome instead.
8.2. Looping with the For-Each Loop¶
You will often loop through all of the elements of an array (to get the average or to get each one to display). You will typically do this using a for-each loop. A for-each loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array. You can step through this code using the Java Visualizer by clicking on the following link link1.
The for-each loop is shown on line 6 above. It says to loop through the array called values
and each time through the loop set the variable val
to the next item in the array. We have to specify the type of val
first since this declares a variable. The type must match the type of objects in the array.
Note
Only use the for-each loop when you want to loop through all the values in an array or list. If you only want to loop through part of an array or list use a for loop instead. Also use a for loop instead of a for-each loop if you want to change any of the values in the array or list.
The code above wasn’t object-oriented. You may have noticed that it was declared to be static. This means that it is a class method not an object method. It is a class method since it doesn’t operate on any object fields - all data that it needs has been passed in to the method. Class methods can be called using ClassName.methodName()
. They can also be called on an object of the class. Object methods can only be called on an object of the class.
A more object-oriented way of doing this would be if the array was a field called values
in the same class as the getAverage
method. Then you don’t need to pass the array values
to the method and the method is an object (instance) method since it operates on the fields of the object. You will typically initialize fields in the constructor as shown below.
- Only I.
- This style of loop does access every element of the array, but using a for-each loop also means the user can access elements through the variable name.
- I and III only.
- Correct! For-each loops access all elements and enable users to use a variable name to refer to array elements, but do not allow users to modify elements directly.
- II and III only.
- For-each loops, as well as allowing users to refer to array elements, run through every element. For-each loops also do not allow users to modify elements directly.
- All of the Above.
- For-each loops access all of an array's elements and allow users to refer to elements through a variable, but do not allow users to modify elements directly.
7-2-2: What are some of the reasons you would use a for-each loop instead of a for loop?
I: If you wish to access every element of an array.
II: If you wish to modify elements of the array.
III: If you wish to refer to elements through a variable name instead of an array index.
You can use the Java Visualizer to step through this code by clicking on the following link link2.
Notice that we have to create an object of the class now in the main
method. Object methods have to be called on an object of the class.
Note
Since values
is an object field and the method getAverage
is in the same class it can directly access the field values
. The code could have also been written as this.values
to indicate the current object’s field called values
. Every object method is passed the object the method was called on and it can be referenced using the Java keyword this
.
Mixed up programs
The following method has the correct code to return the largest value in an integer array called <i>vals</i> (a field of the current object), but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly as well. You will be told if any of the blocks are in the wrong order or not indented correctly.</p>
If you want to step through the correct code to see what it does in the Java Visualizer click on the following link link3.
Some examples of finding the largest value in an array start by setting the largest variable to 0. But, what happens if the array only contains negative numbers? What value could you set largest to and still have it work correctly even if the field vals
contained only negative numbers?
- Whenever the first element in a is equal to val.
- This would be true if the loop started at the end of the array and moved toward the beginning. But, it will loop from the first element to the last.
- Whenever a contains any element which equals val.
- This would be true if temp was only set to the result of checking if the current element in the array is equal to val when it is false. But, it is reset each time through the loop.
- Whenever the last element in a is equal to val.
- The variable temp is assigned to the result of checking if the current element in the array is equal to val. The last time through the loop it will check if the last element is equal to val.
- Whenever only 1 element in a is equal to val.
- There is no count of the number of times the array element is equal to val.
7-2-5: Given that a
is an array of integers and val
is an integer value, which of the following best describes the conditions under which the following code segment will return true?
boolean temp = false;
for ( int i = 0; i < a.length; i++)
{
temp = ( a[i] == val );
}
return temp;
- All values in positions m+1 through myStuff.length-1 are greater than or equal to n.
- Mystery steps backwards through the array until the first value less than the passed num (n) is found and then it returns the index where this value is found.
- All values in position 0 through m are less than n.
- This would be true if mystery looped forward through the array and returned when it found a value greater than the passed num (n).
- All values in position m+1 through myStuff.length-1 are less than n.
- This would be true if it returned when it found a value at the current index that was greater than num (n).
- The smallest value is at position m.
- It returns the first time the condition is met so nothing is known about the values which are unchecked.
7-2-6: Given the following field and method, which of the following best describes the contents of myStuff
after (int m = mystery(n);
) has been executed?
// private field in the class
private int[ ] myStuff;
//precondition: myStuff contains
// integers in no particular order
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
- The values don't matter this will always cause an infinite loop.
- An infinite loop will not always occur in this code segment.
- Whenever a includes a value that is less than or equal to zero.
- When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur.
- Whenever a has values larger then temp.
- Values larger then temp will not cause an infinite loop.
- When all values in a are larger than temp.
- Values larger then temp will not cause an infinite loop.
- Whenever a includes a value equal to temp.
- Values equal to temp will not cause the infinite loop.
7-2-7: Given the following code segment, which of the following will cause an infinite loop? Assume that temp
is an int variable initialized to be greater than zero and that a
is an array of integers.
for ( int k = 0; k < a.length; k++ )
{
while ( a[ k ] < temp )
{
a[ k ] *= 2;
}
}