Section 4.3. Loops

   

4.3 Loops

Because custom functions are defined in ColdFusion script, you are likely to have written in this subset of the ColdFusion language. If you have, that is terrific , because writing loops in CFScript is almost identical to how you write loops and conditional logic statements in Java.

Because loops and conditional logic are a fundamental aspect of any programming language, there is little reason to do more here than examine the syntax, run some example programs so you can get a feel for it, and then move on.

4.3.1 The for Loop

The for loop is typically used to execute a code block a given number of times. The number of iterations is either known in advance or can be discerned at runtime. The syntax is like this:

 for (initialization; test condition; update)  code to execute 

Optionally, you can use curly brackets around the body of the loop:

 for (initialization; test condition; update) {        code to execute } 

The body (the code to be executed) will never be executed if the test condition initially evaluates to false.

Note

The most minimal for loop that can be written is: for ( ; ; ) ; , which would instigate an infinite loop.


A simple for loop looks like this:

 int i;  int j = 10; for (i = 1; i < j; i++) { System.out.println("current value of i:" + i); } 

Excepting the System.out.println in place of the WriteOutput , this syntax is much like you would write in ColdFusion Script. However, Java also supports the use of multiple expressions in the initialization and update sections.

4.3.1.1 MULTIPLE EXPRESSIONS

The for loop supports the use of multiple expressions within its initialization section. The test condition section must be composed of an expression that evaluates to a single boolean value. This is legal

 for ( int i = 0, j = 1;  ;  ; ) 

but it is uncommon to see it in practice, as one variable typically will appear in the initialization, test, and update sections of the loop as well as its body.

The following example creates the variable inside the initialization section of the loop, which is not only legal, but common:

 for (int i = 1; i < 10; i++) { System.out.println("current value of i:" + i); } 

This example also uses a literal value (10) inside the test condition section. When a variable is declared inside the initialization section of the loop in this manner, it is available only to the for statement in which it was created, and its body. For instance, this is not allowed:

 for ( int i = 0; i < 10; i++ ) {     // some code here } // end for loop System.out.print( "i is: " + i ); // error! 

4.3.2 A Nested for Loop

As you would expect, you can nest loops, one inside the other. The following example shows how to create a multiplication table using nested loops.

4.3.3 NestedFor.java

 /*  File: chp4.NestedFor.java Purpose: demonstrates a nested for loop    by printing multiplication table for 10    also demos use of print()  and escape character \t Author: E Hewitt */ public class NestedFor {     public static void main (String[] args) {         int i;         int j;         // outer loop         for (i = 1; i <= 10; i++){             for (j = 1; j <= 10; j++){                 System.out.print(i * j + "\t");             if (j == 10) System.out.println();             }         }     } } // eof 

The listing NestedFor.java demonstrates a few new things. The first is the use of the print() method, which differs from the println() we have been using in that it does not create a carriage return/line feed. We also slipped in an if statement, which we will look at in the next section, though its meaning should be clear. Third, we concatenate to the result of the multiplication operation a string whose contents are \t . This is the escape sequence for a tab and ensures that the output will be evenly spaced .

There are a number of similar escape characters , as shown in Table 4.1.

Table 4.1. Special Character Escape Sequences

Escape Sequence

Item

Unicode Value

  \b  

Backspace

\u0008

  \n  

Line feed

\u000a

  \r  

Carriage return

\u000d

  \t  

Tab

\0009

  \'  

Single quote

\u0027

  \"  

Double quote

\u0022

  \  

Backslash

\u005c

4.3.4 continue

The continue keyword tells a loop to skip the current iteration if some boolean test returns true. Just as in CFScript, to perform this action, you simply write the keyword continue , as shown here:

 // demos use of the continue keyword  // note that it's not a great idea to use // continue in general. public class LoopContinue {     public static void main (String [] args) {         for (int i=1; i < 100; i=i+1){             if ((i % 4) != 0) {                 // if the remainder is not 0                 // then the number is not a                 // multiple of 3             continue;             }             System.out.println(i);         }     } } 

As you are likely to recognize, it's not wonderful to use continue . While there are times when the data you are supplied necessitates it, using continue can be a sign of poorly written code. It's a band -aid job you generally shouldn't have to resort to.

4.3.5 The while Loop

The while loop, like the for loop, is a zero/many iterative loop. That means that the test condition is checked before the body is executed; if the test returns false, the loop will run zero times. Just as with for loops, the while loop in Java is strikingly similar to the ColdFusion Script while , as this listing shows:

4.3.6 while.java

 // demos a while loop  public class LoopWhile {     public static void main (String[] args) {         int time = 10;         int start = 1;         while (time  >= start){             System.out.println(time);             // decrement the value            time--;         }         System.out.println("Happy New Year!");     } } 

4.3.7 The do while Loop

The do while loop, sometimes called a do loop, is a one/many iterative variant of the while loop. That means that the test condition is checked after the body is executed; if the test returns false, the body will be processed once. It is sometimes useful to be able to ensure that the code inside the loop executes at least once.

4.3.8 LoopDoWhile.java

 public class LoopDoWhile {     public static void main(String[] args){ int x; do {    System.out.println("Starting program...");    x = (int) 2 + 2; } while (x != 4);    System.out.println(x + " is 4");  } } 

   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

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