Java Reference
In-Depth Information
{
for (;timesByStart <= timesByEnd; timesByStart++)
{
document.write(timesTable + “ * “ + timesByStart + “ = “ +
timesByStart * timesTable + “<br />”);
}
}
var timesTable;
while ( (timesTable = prompt(“Enter the times table”,-1)) != -1)
{
while (isNaN(timesTable) == true)
{
timesTable = prompt(timesTable + “ is not a valid number, please retry”,-1);
}
if (timesTable == -1)
{
break;
}
document.write(“<br />The “ + timesTable + “ times table<br />”);
writeTimesTable(timesTable,1,12);
}
</script>
</body>
</html>
Save this as ch3_q4.htm .
The function remains the same, so let's look at the new code. The fi rst change from Question 3 is that
you declare a variable, timesTable , and then initialize it in the condition of the fi rst while loop. This
may seem like a strange thing to do at fi rst, but it does work. The code in parentheses inside the while
loop's condition
(timesTable = prompt(“Enter the times table”,-1))
is executed fi rst because its order of precedence has been raised by the parentheses. This will return a
value, and it is this value that is compared to -1 . If it's not -1 , then the while condition is true , and the
body of the loop executes. Otherwise it's skipped over, and nothing else happens in this page.
In a second while loop nested inside the fi rst, you check to see that the value the user has entered is
actually a number using the function isNaN() . If it's not, then you prompt the user to try again, and
this will continue until a valid number is entered.
If the user had entered an invalid value initially, then in the second while loop, that user may have
entered -1 , so following the while is an if statement that checks to see if -1 has been entered. If it has,
you break out of the while loop; otherwise the writeTimesTable() function is called.
Search WWH ::




Custom Search