Java Reference
In-Depth Information
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, you can also use the break statement 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 _ example4.html ) 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>
var degFahren = [212, "string data", ‐459.67];
var degCent = [];
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, you add an if statement to check whether the data in the
degFahren array is not a number. You do this 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 altogether, using the break statement, and code execution continues on the first
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 execution at the next iteration, starting with the for or while statement's condition being
re‐evaluated, just as if the last line of the loop's code had been reached.
In the break example, it was all or nothing—if even one piece of data was invalid, you broke out
of the loop. It might be better if you tried to convert all the values in degFahren , but if you hit an
invalid item of data in the array, you notify the user and continue with the next item, rather than
giving up as the break statement example does:
if (isNaN(degFahren[loopCounter])) {
alert("Data '" + degFahren[loopCounter] + "' at array index " +
loopCounter + " is invalid");
continue;
}
 
Search WWH ::




Custom Search