Making Decisions, Decisions - Making Decisions
(Page 4 of 11 )
The things you’ve learned thus far—how to compare values and how to use Boolean logic to create more complex expressions (or “decisions”)—are the basic tools for controlling the flow of a program. There are many situations where such expressions are useful, and you’ll find few programming problems that don’t require them at one point or another.
Most often, such expressions are combined with control statements, which are statements that control the flow of program execution. There are three basic kinds of control statement:
- Conditional statements: Here the statement is evaluated, and the code block executed depends upon the value returned by the statement.
- Iterative statements: The same block of code is executed again and again (iterated).
- Branching statements: The statement moves execution to a particular point within the code.
The following sections examine each of these in turn.
Introducing Conditional Statements While writing programs you continually come across situations where you need to evaluate a condition and proceed according to the result. Java has two main types of conditional statement:
- The if statement (and its variations)
- The switch statement
The main difference between the two is that an if statement requires an expression that results in either true or false, and switch allows one of many blocks of code to be executed, depending on the outcome of the expression.
Using the if Statement The following is an example of an if statement:
if ( itemQuantity > 0 )
{
System.out.println("The Quantity is greater than 0");
System.out.println("No. of items : " + itemQuantity);
}
In English, what this basically means is this: If the value of itemQuantity is greater than zero, then display the following:
The Quantity is greater than 0
No. of items :
followed by the value of itemQuantity.
Note that this if statement follows the general form of if statements:
if (expression)
{
Statement Block
}
You may recognize the correspondence with the JSTL <if> tag that you’ve already used in earlier chapters’ examples:
<c:if test="expression">
Statement Block
</c:if>
The expression is evaluated first, and if it evaluates to true, the statement block (which consists of one or more Java statements) is executed. In a JSP page the statement block could consist of other tags (HTML or JSP tags) or even plain text.
Be aware that here you see the syntax using a statement block, as denoted by enclosing curly braces. Java doesn’t require that statement blocks be used, and if only a single line is to be executed if the expression evaluates to true, the braces can be omitted, as follows:
if (itemQuantity > 0)
System.out.println("The Quantity is greater than 0");
This practice is frowned upon because mistakes can be made unwittingly. For example, the author doesn’t always maintain the code (they may have left the company, or it may not be their job). So, if the previous code were given to somebody else, that person may want to exit the program if the quantity is greater than zero:
if (itemQuantity > 0)
System.out.println("The Quantity is greater than 0");
System.exit(1);
However, the previous code will actually exit the program no matter what value is stored in itemQuantity. Braces are much safer:
if (itemQuantity > 0) {
System.out.println("The Quantity is greater than 0");
System.exit(1);
}
This applies to all other Java constructs, as well as if, with the exception of do...while loops. Note that this doesn’t apply to the JSTL. The JSTL’s <if> tag, for instance, always requires a closing tag:
<c:if test="expression">Statement Block</c:if>
This requirement is the same as numerous HTML tags, which also require a closing tag, such as the table (<table></table>), heading (<h1></h1>), and font (<font></font>) tags. Although most Web browsers are lenient about this rule, JSP tags aren’t: You must supply the closing tag.
Understanding the if...else Statement
You’ll often find the if statement used in conjunction with else, which allows you to specify code that should be executed when the expression doesn’t evaluate to true:
if (expression)
{
Statement Block 1
}
else
{
Statement Block 2
}
As before, the expression is evaluated first and if it results in true, then the first statement block is executed. If the expression isn’t true, then the second statement block is executed instead.
The following is an example of the if...else statement that evaluates whether you have four or more items to ship. If this is the case, the customer incurs no shipping costs. If you have fewer than four items, you find the shipping cost by multiplying the number of items to ship by the cost of shipping an item:
if (itemQuantity >= 4)
{
shippingCost = 0.0;
}
else
{
shippingCost = basicShippingCost * itemQuantity;
}
So for orders of four or more items, the shippingCost variable will be set to zero. For fewer items than that, the cost will depend on the value of basicShippingCost and the total number of items ordered.
Understanding the if...else if Statement
Many situations are a little more involved, and you don’t simply want to execute one of two options depending on whether a single condition is true or false. For instance, the online store might offer several levels of discount to customers, depending on how much they spend. There might be no discount for purchases less than $100, but between $100 and $500 the customer gets 10 percent off and greater than $500 they get 15 percent off.
You can quite easily code such behavior in Java by simply placing further if statements for each else keyword, as follows:
if (expression1)
{
Statement Block 1
}
else if (expression2)
{
Statement Block 2
}
.
.
More else if Blocks !
.
.
Here, the only statement block that will be evaluated will be the first one where the associated expression evaluates to true (and all previous expressions have come up as false).
Consider the following code snippet, where you test the value of the integer variable n against several possible values. You first check to see if it is less than zero (negative), then check if it’s equal to zero, and finally check if it’s greater than zero (positive):
int n = 10;
if (n < 0 )
{
System.out.println("n is negative");
}
else if (n == 0)
{
System.out.println("n is zero");
}
else if (n > 0)
{
System.out.println("n is positive");
}
Because n is set to 10 at the start of the code snippet, the output will be that n is positive. This is a simple example, but it illustrates the flow of execution well enough for these purposes.
Next: Understanding Variable Scope in Statement Blocks >>
More Java Articles
More By Apress Publishing
|
This article was excerpted from Beginning JSP 2: From Novice to Professional by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391). Check it out at your favorite bookstore. Buy this book now.
|
|