This week, learn all about the different types of loops supportedby JSP, and also expand your knowledge of the various String objectmethods. Finally, take a quick tour of the JSP Response object inpreparation for learning how JSP handles form data.
Both the "while" and "do-while" loops continue to iterate for so long as the specified conditional expression remains true. But there often arises a need to execute a certain set of statements a specific number of times - for example, printing a series of thirteen sequential numbers, or repeating a particular set of <TD> cells five times. In such cases, clever programmers reach for the "for" loop...
The "for" loop typically looks like this:
for (initial value of counter; condition; update counter)
Looks like gibberish? Well, hang in there a
minute...the "counter" here is a JSP variable that is initialized to a numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop, the "condition" is tested - if it evaluates to true, the loop will execute once more and the counter will be appropriately incremented; if it evaluates to false, the loop will be broken and the lines following it will be executed instead.
And here's a simple example that demonstrates how this loop can be used:
<center>Turning The Tables, JSP-Style!</center>
// define the number
int number = 7;
// use a for loop to calculate tables for that number
for (x=1; x<=15; x++)
out.println(number + " X " + x + " = " + (number*x) + "<br>");
And here's the output:
Turning The Tables, JSP-Style!
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
7 X 11 = 77
7 X 12 = 84
7 X 13 = 91
7 X 14 = 98
7 X 15 = 105
Let's dissect this a little bit:
front, a variable is defined, containing the number to be used for the multiplication table; we've used 7 here - you might prefer to use another number.
Next, a "for" loop has been constructed, with "x" as the counter variable. If you take a look at the first line of the loop, you'll see that "x" has been initialized to 1, and is set to run no more than 15 times.
Finally, the println() function is used to take the specified number, multiply it by the current value of the counter, and display the result on the page.