The for is Java’s multipurpose loop controller. It is most commonly used in this form:
for ( int i=0; i<n; i++ ) { out.println(i); }
You can leave out any of the three sections of the
for ( init; should-I-continue-looping?; increment )
sections. If you leave out the should-I-continue-looping? boolean expression, it is assumed true. This means you can use a for to simulate while and do whileloops.
The other common use of for is to iterate over a collection like this:
for ( Iterator aIter = myCollection.iterator(); aIter.hasNext(); ) { Thing item = (Thing) aIter.next(); // do something with item }
Note the empty increment portion of the for. You have to do the next inside the loop body for iterators. for is preferable to using a while loop because the aIter variable is automatically made local to the loop.
For loops can have a dual index, like this:
for ( int i=0, j=n; i<n; i++,j-- ) { /* loop body */ }
or like this:
{ int i,j; for ( i=0,j=n; i<n; i++,j-- ) { /* loop body */ } }or
{ int i; float f; for ( i=0,f=n; i<n; i++,f*=.5 ) { /* loop body */ } }
But, due to a hopelessly muddled for syntax dating back to C, (deriving from the attempt to reuse comma and semicolon in incompatible ways) you cannot write code like this:
for ( int i=0, float f=n; i<n; i++,f*=.5 ) { /* loop body */ }For loops allow two kinds of controlled goto, the break and the continue. break leaps out of the loop entirely. continue jumps to the end of the loop and continues looping. By labeling your for loops with words like inner: and outer: you can break out of two or more levels of nesting with break outer; or continue outer;. break and continue work with while, do while and switch statements as well.
This page is posted |
http://mindprod.com/jgloss/forloop.html | |
Optional Replicator mirror
|
J:\mindprod\jgloss\forloop.html | |
Please read the feedback from other visitors,
or send your own feedback about the site. Contact Roedy. Please feel free to link to this page without explicit permission. | ||
Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[3.144.252.58] |
| |
Feedback |
You are visitor number | |