Java Reference
In-Depth Information
Chapter 3
Exercise 1 Question
A junior programmer comes to you with some code that appears not to work. Can you spot where he
went wrong? Give him a hand and correct the mistakes.
var userAge = prompt(“Please enter your age”);
if (userAge = 0);
{
alert(“So you're a baby!”);
}
else if ( userAge < 0 | userAge > 200)
alert(“I think you may be lying about your age”);
else
{
alert(“That's a good age”);
}
Exercise 1 Solution
Oh dear, our junior programmer is having a bad day! There are two mistakes on the line
if (userAge = 0);
First, he has only one equals sign instead of two in the if 's condition, which means userAge will be
assigned the value of 0 rather than userAge being compared to 0 . The second fault is the semicolon at the
end of the line — statements such as if and loops such as for and while don't require semicolons. The
general rule is that if the statement has an associated block (that is, code in curly braces) then no semi-
colon is needed. So the line should be
if (userAge == 0)
The next fault is with these lines:
else if ( userAge < 0 | userAge > 200)
alert(“I think you may be lying about your age”);
else
The junior programmer's condition is asking if userAge is less than 0 OR userAge is greater than 200 .
The correct operator for a Boolean OR is || , but the programmer has only used one | .
Exercise 2 Question
Using document.write() , write code that displays the results of the 12 times table. Its output should
be the results of the calculations.
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
...
Search WWH ::




Custom Search