Article
The JSP Files - Parts 1 to 8: Tagged and Bagged
Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 Next
The JSP Files -- Part 3: Black Light And White Rabbits
Counting Down
Last time out, you learned a little bit about the various conditional statements and operators available in JSP. This week, we'll expand on those basics by teaching you a little bit about the different types of loops available in JSP, discuss a few more String object methods, and take a quick tour of the new Response object.
First up, loops.
As you may already know, a "loop" is a programming construct that allows you to execute a set of statements over and over again, until a pre-defined condition is met.
The most basic loop available in JSP is the "while" loop, and it looks like this:
while (condition)
{
do this!
}
Or, to make the concept clearer,
while (temperature is below freezing)
{
wear a sweater
}
The "condition" here is a standard conditional expression, which evaluates to either true or false. So, were we to write the above example in JSP, it would look like this:
while (temp <= 0)
{
sweater = true;
}
Here's an example:
<html>
<head>
</head>
<body>
<%!
int countdown=30;
%>
<%
while (countdown > 0)
{
out.println(countdown + " ");
countdown--;
}
out.println("<b>Kaboom!</b>");
%>
</body>
</html>
Here, the variable "countdown" is initialized to 30, and a "while" loop is used to decrement the value of the variable until it reaches 0. Once the value of the variable is 0, the conditional expression evaluates as false, and the lines following the loop are executed.
Here's the output:
30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13
12 11 10 9 8 7 6 5 4 3 2 1 Kaboom!
Doing More With Loops
There's one caveat with the "while" loop. If the conditional expression evaluates as false the first time, the code within the curly braces will never be executed. If this is not what you want, take a look at the "do-while" loop, which comes in handy in situations where you need to execute a set of statements *at least* once.
Here's what it looks like:
do
{
do this!
} while (condition)
For example, the following lines of code would generate no output whatsoever, since the conditional expression in the "while" loop would always evaluate as false.
<%
int bingo = 366;
while (bingo == 699)
{
out.println ("Bingo!");
break;
}
%>
However, the construction of the "do-while" loop is such that the statements within the loop are executed first, and the condition to be tested is checked after. Using a "do-while" loop implies that the code within the curly braces will be executed at least once - regardless of whether or not the conditional expression evaluates as true.
<%
int bingo = 366;
do
{
out.println ("Bingo!");
break;
} while (bingo == 699);
%>
Try it yourself and see the difference.
Copyright Melonfire, 2000. All rights reserved.