Java Reference
In-Depth Information
3.
Execute code in the block after the for statement.
4.
Execute the increment part of the for statement.
5.
Repeat steps 2 through 4 until the test condition is false.
Try It Out Converting a Series of Fahrenheit Values
Let's change the temperature converter so that it converts a series of values, stored in an array, from
Fahrenheit to centigrade. You will be using the for statement to go through each element of the array.
Type the code and save it as ch3_examp4.htm.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/javascript”>
var degFahren = new Array(212, 32, -459.15);
var degCent = new Array();
var loopCounter;
for (loopCounter = 0; loopCounter <= 2; loopCounter++)
{
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
}
for (loopCounter = 2; loopCounter >= 0; loopCounter--)
{
document.write(“Value “ + loopCounter + “ was “ + degFahren[loopCounter] +
“ degrees Fahrenheit”);
document.write(“ which is “ + degCent[loopCounter] +
“ degrees centigrade<br />“);
}
</script>
</body>
</html>
On loading this into your browser, you'll see a series of three lines in the page, containing the results of
converting our array of Fahrenheit values into centigrade (as shown in Figure 3-11).
Value 2 was -459.15 degrees Fahrenheit which is -272.8611111111111 degrees centigrade
Value 1 was 32 degrees Fahrenheit which is 0 degrees centigrade
Value 0 was 212 degrees Fahrenheit which is 100 degrees centigrade
Figure 3-11
The fi rst task is to declare the variables you are going to use. First, you declare and initialize degFahren
to contain an array of three values: 212, 32, and -459.15. Next, degCent is declared as an empty array.
Search WWH ::




Custom Search