Java Reference
In-Depth Information
exercise 1 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5: Question 1</title>
</head>
<body>
<script>
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 12);
document.write("Date 12 months ahead is " + nowDate.getDate());
document.write(" " + months[nowDate.getMonth()]);
document.write(" " + nowDate.getFullYear());
</script>
</body>
</html>
Save this as ch5 _ question1.html .
Because the getMonth() method returns a number between 0 and 11 for the month rather than its
name, an array called months has been created that stores the name of each month. You can use
getMonth() to get the array index for the correct month name.
The variable nowDate is initialized to a new Date object. Because no initial value is specified, the
new Date object will contain today's date.
To add 12 months to the current date you simply use setMonth() . You get the current month value
with getMonth() , and then add 12 to it.
Finally you write the result out to the page.
exercise 2 Question
Obtain a list of names from the user, storing each name entered in an array. Keep getting another
name until the user enters nothing. Sort the names in ascending order and then write them out to
the page, with each name on its own line.
exercise 2 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5: Question 2</title>
</head>
<body>
<script>
Search WWH ::




Custom Search