Branching, Looping, and Creating Methods in JSP
Today we're going to get some more essential Java programming under our belts. We'll see three crucial techniques herebranching, looping, and creating methods. These are all basic skills for the JSP programmer, and we'll need them in our programming arsenal throughout the book. Here's an overview of today's topics:
Branching statementsif and switch
Looping statementsfor, while, and do-while
Creating methods
Passing data to methods
Returning data from methods
Branching statements (also called conditional statements) let you make decisions in code. For example, we've already seen the most popular Java branching statement at workthe if statementin Day 2, "Handling Data and Operators." In example ch02_15.jsp, we used the if statement to display the message "Picnic time!" if the temperature was between 60 and 90 degrees Fahrenheit:
<HTML> <HEAD> <TITLE>Using Logical Operators</TITLE> </HEAD> <BODY> <H1>Using Logical Operators</H1> <% int temperature = 70; if (temperature < 90 && temperature > 60) { out.println("Picnic time!"); } %> </BODY> </HTML>
You'll see more about branching statements like this one today.
Loops let you execute some code over and over on a set of data. Loops are one of the main reasons computers are so powerful, because that's what computers are good at: executing large amounts of code quickly. For example, you might have an array holding student scores from a class you're teaching on JSP, and using a loop, you can add all the scores to find the average score. Each time through the loop, called a loop iteration, you can increment the array index, giving you access to the next array element. As you iterate through the whole array of student scores this way, you can add each score to a running total. When the loop is finished, you can divide the running total by the total number of students to get the average score. You'll see how that works today.
We'll also see how to create our own methods today. We've seen methods ever since Day 1, where we used the out object's println method to write text to the Web page being sent back to the browser. Here, we're going to see how to write our own methods. Dividing your code into methods is a good idea when your code gets long; it helps keep things organized. Unless you break your code up into smaller units, you could end up with many pages of tangled Java. If you divide that code into methods, each of which is called to execute a specific, discrete task, things stay manageable.
That's it for the introductionlet's get programming, starting with branching statements.
Branching Statements
The next step up from using the simple operators we saw in Day 2 is to use branching statements in your code. You use branching statements to make decisions based on the value of your data, and to make the flow of the program go in different directions accordingly.
There are two branching statements in Javathe if statement, and the switch statement.
The if Statement
When you want to test conditions and execute code accordingly, it's a good idea to use a statement like the if statement. Here's how you use this statement in general:
if (condition) statement1; [else statement2;]
If condition evaluates to true, statement1 is executed. Otherwise, if there is an else clause to the statement, the code in it (statement2) is executed.
In Java, statement1 and statement2 can both be compound statements, which means that they can be made up of a number of statements enclosed in curly braces, like this:
if (condition){ statement; statement; . . . } else { statement; statement; . . . }
Let's take a look at some examples to see how this works. For example, what if you wanted to find the absolute value of a number? One way to get an absolute value is to start by checking whether the value is greater than 0, and if so, just print out the value itself. Listing 3.1 shows how to make that test with an if statement.
Listing 3.1 Using an if Statement (ch03_01.jsp)
<HTML> <HEAD> <TITLE>Using the if Statement</TITLE> </HEAD> <BODY> <H1>Using the if Statement</H1> <% int value = 10; if(value > 0) out.println("Absolute value of " + value + " = " + value); %> </BODY> </HTML>
Note the if statement's condition here, value > 0, where the code is using the > relational operator (see the section "Relational Operators" in Day 2), which will be true if the value is greater than 0, and false otherwise. You can see the results of this code in Figure 3.1.
Figure 3.1 Using the if statement.
Executing Compound Statements
Note that in this case, the statement that's executed if the if statement is true is a single statement, but you can also execute multiple statements if you make them part of a compound statement surrounded by { and }, as you see in Listing 3.2.
Listing 3.2 Using a Compound Statement (ch03_02.jsp)
<HTML> <HEAD> <TITLE>Using Compound Statements</TITLE> </HEAD> <BODY> <H1>Using Compound Statements</H1> <% int value = 10; if(value > 0) { out.println("The number was positive."); out.println("Absolute value of " + value + " = " + value); } %> </BODY> </HTML>
You can see the results of this code in Figure 3.2.
Figure 3.2 Using compound statements.
The else Statement
So far, our if statement only displays an absolute value if the value is greater than 0. You can expand that if statement by adding an else clause, which is executed if the if statement's condition is false. You can see how that looks in Listing 3.3. This enables us to find the absolute value of negative numbers as well as positive ones (note that the code is also using the Java negation operator (-) to change the sign of value if needed; see the topic "Operators" in Day 2 for more on this operator).
Listing 3.3 Using an else Clause (ch03_03.jsp)
<HTML> <HEAD> <TITLE>Using an else Clause</TITLE> </HEAD> <BODY> <H1>Using an else Clause</H1> <% int value = -10; if(value > 0) { out.println("Absolute value of " + value + " = " + value); } else { out.println("Absolute value of " + value + " = " + -value); } %> </BODY> </HTML>
You can see the results of this code in Figure 3.3.
Figure 3.3 Using an else clause.
Nested if Statements
You can also nest if statements inside each other; here's an example showing how that works. In this case, say that you want to display the reciprocal of a numberbut only if that number is positive. Also, you don't want to even try to get the reciprocal if the number is zero, because the reciprocal of zero is not defined. Listing 3.4 shows how you can put all this into code using a nested if statement (note that the code is using the relational operator != here, which means "not equal to," as you saw in Day 2).
Listing 3.4 Nested if Statements (ch03_04.jsp)
<HTML> <HEAD> <TITLE>Nested if Statements</TITLE> </HEAD> <BODY> <H1>Nested if Statements</H1> <% double value = 2; if (value != 0) { if (value > 0) out.println("The result = " + (1 / value)); else out.println("Sorry, we need a positive number."); } %> </BODY> </HTML>
if-else Ladders
It's possible to create an entire sequence of if-else statements called an if-else ladder. You can see an example showing how this works in Listing 3.5; in this case, the code keeps testing the value in a String variable until it finds a match to the current day of the week.
Listing 3.5 Using an if-else Ladder (ch03_05.jsp)
<HTML> <HEAD> <TITLE>Using an if-else Ladder</TITLE> </HEAD> <BODY> <H1>Using an if-else Ladder</H1> <% String day = "Friday"; if(day == "Monday") out.println("It\'s Monday."); else if (day == "Tuesday") out.println("It\'s Tuesday."); else if (day == "Wednesday") out.println("It\'s Wednesday."); else if (day == "Thursday") out.println("It\'s Thursday."); else if (day == "Friday") out.println("It\'s Friday."); else if (day == "Saturday") out.println("It\'s Saturday."); else if (day == "Sunday") out.println("It\'s Sunday."); %> </BODY> </HTML>
You can see the results of this code in Figure 3.4, where we see that it's Friday.
Figure 3.4 Using an if-else ladder.
Although it's possible to create if-else ladders like this, Java actually includes a statement expressly for situations like this: the switch statement.
The switch Statement
The switch statement is Java's multiway branch statement, and it provides the same kind of functionality as an if-else ladder, but in a much easier form. Here's what the switch statement looks like in general:
switch (expression) { case value1: statement1; [break;] case value2: statement2; [break;] case value3: statement3; [break;] . . . default: default_statement; }
Here, the value of the expression, which must be of type byte, char, short, or int, is compared against the various test values in the case statements: value1, value2, and so on. If the expression matches one of the test values in the case statements, the code associated with that case statement is executed. If execution reaches a break statement, the switch statement ends.
Listing 3.6 shows an example in which the code displays the day of the week based on a numeric value using a switch statement.
Listing 3.6 Using the switch Statement (ch03_06.jsp)
<HTML> <HEAD> <TITLE>Using the switch Statement</TITLE> </HEAD> <BODY> <H1>Using the switch Statement</H1> <% int day = 3; switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday."); break; default: out.println("It must be Saturday."); } %> </BODY> </HTML>
You can see the results of this code in Figure 3.5.
Figure 3.5 Using the switch statement.
Take a look at this switch statement; note that each case statement in the switch statement matches a particular value of the day variable. If the value in day matches that given in a specific case statement, the code in that case statement is executed, up to the break statement, which ends the switch statement:
int day = 3; switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday."); break; default: out.println("It must be Saturday."); }
You can have multiple statements in each case statement if you so desire:
case 1: out.println("It\'s Monday.<BR>"); out.println("Have you had your coffee yet?<BR>"); out.println("Time to go to work...<BR>"); break;
Note also the (optional) default statement at the end of the switch statement in the exampleif no case statement is executed, the code in the default statement, if there is one, is executed. You can even nest switch statements, just like if statements.
If you don't place a break statement at the end of a case statement, execution will continue with the code in the next case statement. Sometimes that's useful, as when you want to execute the same code for multiple case test values, as you see in Listing 3.7.
Listing 3.7 Testing for Multiple Conditions (ch03_07.jsp)
<HTML> <HEAD> <TITLE>Testing for Multiple Conditions</TITLE> </HEAD> <BODY> <H1>Testing for Multiple Conditions</H1> <% int temperature = 64; switch(temperature) { case 60: case 61: case 62: out.println("Sorry, too cold!"); break; case 63: case 64: case 65: out.println("Pretty cool."); break; case 66: case 67: case 68: case 69: out.println("Nice!"); break; case 70: case 71: case 72: case 73: case 74: case 75: out.println("Fairly warm."); break; default: out.println("Too hot!"); } %> </BODY> </HTML>
You can see the results of this code in Figure 3.6, where we see that the temperature is pretty cool.
Figure 3.6 Testing for multiple conditions in a switch statement.
That completes our look at branching statements; next, we'll look at loops.