The JSP Files (part 4): The Red Pill - A Chocolate Addiction
(Page 7 of 9 )
In order to modify an element of an array, you would simply assign a new value to the corresponding variable. If you wanted to replace "chocolate fudge cake" with "chocolate chip cookies", you'd simply use
<%
desserts[3] = "chocolate chip cookies";
%>
and the array would now read
String[] desserts = {"chocolate mousse", "tiramisu", "apple pie",
"chocolate chip cookies"};
JSP arrays can only store the type of data specified at the time of declaring the array variable; a string array cannot hold numbers, or vice-versa.
And finally, you can obtain the number of items in an array with the "length" property - the following example demonstrates this:
<html><head><basefont face="Arial"></head><body><%// define an arrayString[] desserts = {"chocolate mousse", "tiramisu", "apple pie","chocolate fudge cake"};// display array lengthout.println("The dessert menu contains " + desserts.length + " items."); %> </body></html>
And the output is:
The dessert menu contains 4 items.
You can use a "for" loop to iterate through the elements of an array, as the following example demonstrates.
<html><head><basefont face="Arial"></head><body>Desserts available:<ul><%// define counterint counter;// define an arrayString[] desserts = {"chocolate mousse", "tiramisu", "apple pie","chocolate fudge cake"};for (counter=0; counter<desserts.length; counter++){out.println("<li>" + desserts[counter] + "<br>");} %></ul></body></html>
And the output is:
Desserts available:
- chocolate mousse- tiramisu- apple pie- chocolate fudge cake
Next: Couch Potato >>
More Java Articles
More By Vikram Vaswani, (c) Melonfire