Java Reference
In-Depth Information
Now when five states need to be added, the programmer must enter five
if/else
statements and ten start and
end
OPTION
tags. That's a lot of typing and, of course, this means mistakes can easily be made. To cut down on the
amount of “hard-coded” HTML, a
String
array will hold the state values and a
for
loop will:
1.
Read each value in the array
2.
Check if the array value is the selected value
Build the appropriate
OPTION
tags.
3.
Tutorial: Using an Array
Now let's use an array
In TNTStateDDM, add the following statements to create a class
String
array variable
called stateArray that has the following three values.
1.
String[] stateArray = {"FL", "GA", "OK"};
Notice that no size was specified for the array. An array can be assigned values, and the JVM will create an array
of the needed size - in this case three.
In TNTStateDDM, add the following statements to create class
StringBuffer
variables to
hold various “pieces” of the
OPTION
tags.
2.
StringBuffer optionTagStart = new StringBuffer("<OPTION value=\"");
StringBuffer optionSelected = new StringBuffer("\" selected>");
StringBuffer optionNotSelected = new StringBuffer("\">");
StringBuffer optionTagEnd = new StringBuffer("</OPTION>");
StringBuffer optionTags =
new
StringBuffer();
Because the HTML to define each option will be constantly changing in the loop, defining optionTags as a
StringBuffer
is a more computer-efficient choice than defining it as a
String
. However, because only
Strings
can be
embedded into the JSP, we will need to convert the
StringBuffer
to a
String t
hereby adding a little extra code.
Notice that when a state is to be selected, only the start tag is different from a non-selected state. In other words,
the end tag never changes. Looking closer at the start tags, notice that non-selected and selected
OPTION
tags actually
begin the same. The difference is the characters that follow the value attribute in the start tag. If a value is not selected,
then the value in the start tag is simply followed by a double quote and a greater than sign. If the value is selected,
then it is followed by a double quote, a space, the keyword
selected
, and then the greater than sign. So, two strings
(optionSelected and optionNotSelected) were created to hold these two possible sets of characters.
3.
In the doStartTag, between the two write statements, insert the following statements
for
(
int
ctr = 0; ctr < stateArray.length; ctr++) {
optionTags.append(optionTagStart).append(stateArray[ctr]);
if
(stateArray[ctr] ==
this
.selected) {
optionTags.append(optionSelected);
}
else
{
optionTags.append(optionNotSelected);
}
optionTags.append(stateArray[ctr]).append(optionTagEnd);
pageContext.getOut().write(String.
valueOf
(optionTags));
optionTags.delete(0,optionTags.length());
}