Section A.3. Loops


[Page 546]

A.3. Loops

If you are using Java 5.0 (1.5) you can use a for-each loop. The syntax for a for-each loop is:

for (type name : collection) {  // statements to execute }


The type is the type of objects in the collection. The name is the local variable name to use. The collection is anything that holds a collection of objects, such as an array, list, or set. The following is an example of using a for-each loop:

// loop through all the samples in the array for (SoundSample sample : sampleArray) {    value = sample.getValue();    sample.setValue(value * 2); }


If you know how many times a loop should repeat, then use a for loop. The syntax for a for loop is:

for (initializationArea; continuationTest; changeArea) {    // statements in the for loop }


You can declare and initialize local variables in the initialization area. You specify a boolean expression for the continuation test. The loop will continue while the test is true. The change area is where you specify how to change variables after each execution of the loop.

// loop through all the pixels for (int i=0; i < pixelArray.length; i++)     pixelArray[i].setBlue(0);


If you don't know how many times a loop should repeat, then use a while loop. The syntax of a while loop is:

while (continuationTest) {    // statements in the while loop }


The statements in the curly braces will be executed as long as the continuation test is true. Often you will initialize variables before the while loop begins and change them just before the end of the while loop statements. But you can do this in the continuation test.


[Page 547]
// Loop while there is more data while((line = reader.readLine()) != null) { // print the current line System.out.println(line); }




Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net