CSCI111: Chapter 5

CSCI111: Notes Chapter 5
Loops - Repetition


Repetition - while, do and for

There are three ways in Java to do loops Rather than writing the same piece of code over and over again, you can tell the control to repeat...loop around.

A loop consists of three major parts:

Different constructs (do, while,for) all do these, but at different points in the code. Failure to do these could result in infinite loops.

The books first example is to show how you could make a bunch of asterisks,

Say, rather than

g.drawString("********", 10, 10);

we try

The way cool applet

Where, in this code did we: initialize the variable, increment it, check for the end of looping?

And here is a very similar example using lines, along with code

Put these ideas together to get some steps

HA!!! In the book this came from, it says at the adjustmentValueChanged method, "hanged". This is pretty funny because the code does hang. What does that mean? They must not have ever fixed it or seen that in the text when they finished it.

The grammatical structure for a while loop is

The grammatical structure for a do loop is
For for loops, we have all the three components in one construct or Asterisks using for and code

For loops are usually used when the number of iterations is known in advance.

Java 1.5 introduced an additional format for for's (used by other languages as well).
The enhanced for is like a for "each" in an array. It goes through each member in the array one at a time (like array.length and i++ by default)

Here is an example from the Java Tutorial:

class EnhancedForDemo {
     public static void main(String[] args){
          int[] numbers = {1,2,3,4,5,6,7,8,9,10};
          for (int item : numbers) {
            System.out.println("Count is: " + item);
          }
     }
}

With such a loop, you can also create arrays of Objects from arrays of primitive data types: see autoboxing

Finally, an infinite loop (on purpose)

     for ( ; ; ) {    // infinite loop
        // code to do here
     }