Java Reference
In-Depth Information
Note that within the while statement's condition, you are using the isNaN() function that you saw in
Chapter 2. This checks whether the userAge variable's value is NaN (not a number). If it is not a num-
ber, the condition returns a value of true; otherwise it returns false. As you can see from the example,
it enables you to test the user input to ensure the right data has been entered. The user might lie about
his age, but at least you know he entered a number!
The do...while loop is fairly rare; there's not much you can't do without it, so it's best avoided unless
really necessary.
The break and continue Statements
You met the break statement earlier when you looked at the switch statement. Its function inside a
switch statement is to stop code execution and move execution to the next line of code after the closing
curly brace of the switch statement. However, the break statement can also be used as part of the for
and while loops when you want to exit the loop prematurely. For example, suppose you're looping
through an array, as you did in the temperature conversion example, and you hit an invalid value. In
this situation, you might want to stop the code in its tracks, notify the user that the data is invalid, and
leave the loop. This is one situation where the break statement comes in handy.
Let's see how you could change the example where you converted a series of Fahrenheit values
(ch3_examp4.htm) so that if you hit a value that's not a number you stop the loop and let the user
know about the invalid data.
<script language=”JavaScript” type=”text/javascript”>
var degFahren = new Array(212, “string data”, -459.67);
var degCent = new Array();
var loopCounter;
for (loopCounter = 0; loopCounter <= 2; loopCounter++)
{
if (isNaN(degFahren[loopCounter]))
{
alert(“Data '“ + degFahren[loopCounter] + “' at array index “ +
loopCounter + “ is invalid”);
break;
}
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
}
You have changed the initialization of the degFahren array so that it now contains some invalid data.
Then, inside the for loop, an if statement is added to check whether the data in the degFahren array
is not a number. This is done by means of the isNaN() function; it returns true if the value passed to
it in the parentheses, here degFahren[loopCounter], is not a number. If the value is not a number,
you tell the user where in the array you have the invalid data. Then you break out of the for loop alto-
gether, using the break statement, and code execution continues on the fi rst line after the end of the
for statement.
That's the break statement, but what about continue? The continue statement is similar to break in
that it stops the execution of a loop at the point where it is found, but instead of leaving the loop, it starts
Search WWH ::




Custom Search