Java Reference
In-Depth Information
<head>
<title>Chapter 5: Question 1</title>
</head>
<body>
<script type=”text/javascript”>
var months = new Array(“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 ch05_q1.htm .
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 specifi ed, 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 PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 5: Question 2</title>
</head>
<body>
<script type=”text/javascript”>
var inputName = “”;
Search WWH ::




Custom Search