Java Reference
In-Depth Information
4. Recall that the main method provides the starting point and ordering for the execution of your
program. An enhanced for loop will iterate through the elements of an array, but first you must
declare an array for this:
int[] tenIntegers = {1,2,3,4,5,6,7,8,9,10};
It should be placed after (String[] args){ and before the next } .
5. Now add the following enhanced for loop immediately after the array declaration.
for (int i : tenIntegers){
}
6. Now insert the statements that will be executed during each loop. On each iteration, you will mul-
tiply the value of the current array entry by 2 (doubling it) and then print a string containing the
resulting value to the console. Use the following statements to do so:
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
Place these statements between the { } of the for loop.
7. Finally, add a print statement to indicate the end of the program. Use the following statement:
System.out.println("End of program");
This time, make sure it is placed after the closing bracket (}) of the for loop, but before the clos-
ing bracket (}) of the main method. This ensures that it will not be repeated on each iteration,
but it will be executed once before the main method concludes.
8. Your class body should now look like this:
public class EnhancedForLoop {
public static void main(String[] args){
for (int i : tenIntegers){
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
}
System.out.println("End of program");
}
}
9. Save the class by clicking the disk icon or selecting File, then Save.
10. Run the application by clicking the green play icon or selecting Run, and then Run.
How It Works
Now take a look at how it works.
1. The application begins by executing the main method, which in this case is the only method.
2. The first statement creates a new integer array with ten entries.
Search WWH ::




Custom Search