HomeJava & J2EE Page 4 - The JSP Files (part 2): Attack Of The Killer Fortune Cookies
Cookie-Cutter Code - Java
The second part of our introductory JSP tutorial discussesarithmetic, logical and comparison operators, together with simple examplesand illustrations. You'll also learn the basics of JSP's numerousconditional expressions, including the "if", "if-else" and "switch"statements, and find out a little more about the String object.
The "if-else" construct certainly offers a smidgen more flexibility than the basic "if" construct, but still limits you to only two possible courses of action. If your script needs to be capable of handling more than two possibilities, you should reach for the "if-else if-else" construct, which is a happy combination of the two constructs you've just been reading about.
if (first condition is true)
{
do this!
}
else if (second condition is true)
{
do this!
}
else if (third condition is true)
{
do this!
}
... and so on ...
else
{
do this!
}
Take a look at it in action:
<%!
// declare temperature variable
int temp = 20;
%>
<%
// check temperature and display output
// what happens if temp is less than 25 degrees
if (temp > 25)
{
out.println("Man, it's hot out there!");
}
// what happens if temp is between 25 and 10 degrees
else if (temp < 25 && temp > 10)
{
out.println("Great weather, huh?!");
}
// what happens if temp is less than ten degrees
else if (temp < 10)
{
out.println("Man, it's freezing out there!");
}
// this is redundant, included for illustrative purposes
else
{
out.println("Huh? Somebody screwed up out there!");
}
%>
In this case, depending on the value of the "temp" variable,
the appropriate code branch is executed, thereby making it possible to write scripts which allow for multiple possibilities.
One important point to be noted here: control is transferred to successive "if" branches only if the preceding condition(s) turn out to be false. Or, in English, once a specific conditional expression is satisfied, all subsequent conditional expressions are ignored.
Here's another example, this one using the day of the week to decide which fortune cookie to display. Alter the "day" variable to see a different cookie each time.
<%!
String day = "Monday";
String fortune;
%>
<%
// check day and set fortune
if (day.equals("Monday"))
{
fortune = "Adam met Eve and turned over a new leaf.";
}
else if (day.equals("Tuesday"))
{
fortune = "Always go to other people's funerals, otherwise they won't come
to yours.";
}
else if (day.equals("Wednesday"))
{
fortune = "An unbreakable toy is useful for breaking other toys.";
}
else if (day.equals("Thursday"))
{
fortune = "Be alert - the world needs more lerts.";
}
else if (day.equals("Friday"))
{
fortune = "Crime doesn't pay, but the hours are good.";
}
else
{
fortune = "Sorry, closed on the weekend";
}
// print output
out.println(fortune);
%>