web technologies comp6115 session 3: designing, constructing, testing and debugging dynamic web...

98
Web Technologies Web Technologies COMP6115 COMP6115 Session 3: Designing, Constructing, Testing Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites and Debugging Dynamic Web Sites Dr. Paul Walcott Dr. Paul Walcott Department of Computer Science, Mathematics and Physics Department of Computer Science, Mathematics and Physics University of the West Indies, Cave Hill Campus University of the West Indies, Cave Hill Campus Barbados Barbados 04/12/06 © 2006/2007 Dr. Paul Walcott

Upload: pearl-simon

Post on 12-Jan-2016

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Web Technologies Web Technologies COMP6115COMP6115

Session 3: Designing, Constructing, Testing Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sitesand Debugging Dynamic Web Sites

Dr. Paul WalcottDr. Paul WalcottDepartment of Computer Science, Mathematics and PhysicsDepartment of Computer Science, Mathematics and PhysicsUniversity of the West Indies, Cave Hill CampusUniversity of the West Indies, Cave Hill CampusBarbadosBarbados04/12/06

© 2006/2007 Dr. Paul Walcott

Page 2: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Session ObjectivesSession Objectives

• After completing this session you will After completing this session you will be able to:be able to:– Comprehend how to test and debug a Comprehend how to test and debug a

dynamic Web sitedynamic Web site– Construct a dynamic Web siteConstruct a dynamic Web site

Page 3: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

IntroductionIntroduction1,2,3,4,51,2,3,4,5

• So far we have only created static So far we have only created static Web pagesWeb pages

• In order to create dynamic Web In order to create dynamic Web pages we need to use DHTML pages we need to use DHTML (Dynamic HTML) and a scripting (Dynamic HTML) and a scripting languagelanguage

• The scripting language that will be The scripting language that will be used is JavaScriptused is JavaScript

Page 4: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScriptJavaScript

• JavaScript unfortunately is not JavaScript unfortunately is not available in all browsersavailable in all browsers

• It is implemented in:It is implemented in:– Netscape Navigator 2.0 and later Netscape Navigator 2.0 and later

versionsversions– Internet Explorer 3.0 and later versionsInternet Explorer 3.0 and later versions

Page 5: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScript Cont’dJavaScript Cont’d

• JavaScript:JavaScript:– Is client-basedIs client-based– Provides simple interactions with the Provides simple interactions with the

useruser– Provides navigation through pagesProvides navigation through pages– Validates form informationValidates form information

Page 6: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScript Cont’dJavaScript Cont’d

• JavaScript was not designed to:JavaScript was not designed to:– Write files to the system serverWrite files to the system server– Write files to the client’s machineWrite files to the client’s machine– Read files from the client machineRead files from the client machine– Handle graphics; that is, it does not Handle graphics; that is, it does not

have graphic capablitieshave graphic capablities

Page 7: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScript Cont’dJavaScript Cont’d

• Before we can begin writing Before we can begin writing JavaScript programs however, the JavaScript programs however, the student must first be introduced to student must first be introduced to computer programmingcomputer programming

Page 8: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer ProgrammingComputer Programming

What is a Computer Program?What is a Computer Program?• A computer program is:A computer program is:

– A computer program is a set of A computer program is a set of statements or instructions to be used statements or instructions to be used directly or indirectly in a computer in directly or indirectly in a computer in order to bring about a certain result order to bring about a certain result (www.tms.org/pubs/journals/JOM/matters/matters-9710.html )(www.tms.org/pubs/journals/JOM/matters/matters-9710.html )

• A computer program requires some A computer program requires some input, which is processed to generate input, which is processed to generate a given outputa given output

Page 9: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

What is a Computer Program What is a Computer Program (Cont’d)?(Cont’d)?

• When given a problem you must:When given a problem you must:– Determine the inputDetermine the input– Determine the outputsDetermine the outputs– Determine the processing required to Determine the processing required to

transform the inputs to the desired transform the inputs to the desired outputoutput

Page 10: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dHow is a Computer Program Described?How is a Computer Program Described?

• A computer program is described using an A computer program is described using an algorithmalgorithm– An algorithm is like a recipe which describes An algorithm is like a recipe which describes

the set of steps required to cook a given dishthe set of steps required to cook a given dish

• An algorithm may take several forms, An algorithm may take several forms, however popular techniques include:however popular techniques include:– FlowchartsFlowcharts– Pseudo-codePseudo-code

Page 11: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dImportant Programming ConceptsImportant Programming Concepts• There are several important concepts that There are several important concepts that

must be understood in order to write an must be understood in order to write an algorithm and a computer program. These algorithm and a computer program. These include:include:– VariablesVariables– TypesTypes– AssignmentAssignment– Incrementation/decrementationIncrementation/decrementation– ConditionalsConditionals– LoopingLooping– ArraysArrays

Page 12: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dVariablesVariables• A variable is a name/value pairA variable is a name/value pair

– E.g. the variable named Price might have the E.g. the variable named Price might have the value 10.00, or the variable Count the value 1value 10.00, or the variable Count the value 1

• Variables in computer programs are Variables in computer programs are associated with a given location in the associated with a given location in the computer’s memorycomputer’s memory

• Variable names typically begin with a Variable names typically begin with a letter (or underscore character) but may letter (or underscore character) but may include letters, the underscore character include letters, the underscore character and numbers in subsequent charactersand numbers in subsequent characters

Page 13: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Temporary VariablesTemporary Variables

• A temporary variable is a variable A temporary variable is a variable that is used to temporarily hold a that is used to temporarily hold a given valuegiven value– An example of when a temporary An example of when a temporary

variable is required is when the value in variable is required is when the value in two variables need to be swapped two variables need to be swapped around (this is discussed later)around (this is discussed later)

Page 14: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dVariable TypesVariable Types• The variable type specifies the type of The variable type specifies the type of

information that it can holdinformation that it can hold• Some common types are:Some common types are:

– Integers, e.g. 10 or -20Integers, e.g. 10 or -20– Floats (or real numbers), e.g. 5.67Floats (or real numbers), e.g. 5.67– Characters, which are single characters enclosed in a Characters, which are single characters enclosed in a

single brace, e.g. ‘a’ or ‘z’single brace, e.g. ‘a’ or ‘z’– Strings, which are a sequence of characters, e.g. “fred”Strings, which are a sequence of characters, e.g. “fred”

• An empty string is referred to as a null string, i.e. “”An empty string is referred to as a null string, i.e. “”– Boolean, which has a value of True or FalseBoolean, which has a value of True or False

Page 15: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dAssignmentAssignment• In order for a variable to get a value, this value In order for a variable to get a value, this value

must be assigned to itmust be assigned to it• Giving a variable a value for the first time is Giving a variable a value for the first time is

known as initialisationknown as initialisation• An assignment may come in several forms, for An assignment may come in several forms, for

example:example:– Count = 1Count = 1– Product = “ShoesProduct = “ShoesWhere the integer 1 is assigned to the variable count and Where the integer 1 is assigned to the variable count and

the string “Shoes” is assigned to the variable Productthe string “Shoes” is assigned to the variable Product

Page 16: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dAssignment Cont’dAssignment Cont’d

• Note that the value on the right hand side Note that the value on the right hand side is assigned to the variable on the left hand is assigned to the variable on the left hand side.side.

• In a similar way two variables may be used In a similar way two variables may be used in an assignment, e.g.:in an assignment, e.g.:– Count = NewCountCount = NewCount

Where the value of the variable NewCount is Where the value of the variable NewCount is assigned to the variable Countassigned to the variable Count

Page 17: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dAssignment Cont’dAssignment Cont’d• Using the concept of assignment and Using the concept of assignment and

temporary variables the value stored temporary variables the value stored in two variables my be exchangedin two variables my be exchanged

• Consider the variables a and b as Consider the variables a and b as defined below:defined below:– a = 1a = 1– b = 2b = 2

Page 18: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dAssignment Cont’dAssignment Cont’d• If we attempted to swap these values If we attempted to swap these values

directly then one of the values would be directly then one of the values would be lost:lost:a = ba = bb = ab = aWill result in both a and b being equal to 2Will result in both a and b being equal to 2

• SimilarlySimilarlyb = ab = aa = ba = bWill result in both a and b being equal to 1Will result in both a and b being equal to 1

Page 19: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dAssignment Cont’dAssignment Cont’d• In order to complete this swap correctly, a In order to complete this swap correctly, a

temporary variable needs to be used:temporary variable needs to be used:temp = atemp = aa = ba = bb = tempb = temp

• AlternativelyAlternativelytemp = btemp = bb = ab = aa = tempa = temp

Page 20: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dIncrementation/DecrementationIncrementation/Decrementation• Often in computer programming it is Often in computer programming it is

necessary to count the number of times a necessary to count the number of times a given even occurs, or should occurgiven even occurs, or should occur

• A variable is often used in this situation A variable is often used in this situation and is often called a counterand is often called a counter

• A Counter may be of two forms:A Counter may be of two forms:– One that incrementsOne that increments– One that decrementsOne that decrements

Page 21: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Incrementation/Decrementation Incrementation/Decrementation Cont’dCont’d

• When incrementing, the value of the When incrementing, the value of the counter is increased by one. e.g.counter is increased by one. e.g.– Count = Count + 1Count = Count + 1

•This means that the new value of the This means that the new value of the variable count will get the old value of count variable count will get the old value of count plus one; if count was initially 5 its new plus one; if count was initially 5 its new value will be 6value will be 6

Page 22: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Incrementation/Decrementation Incrementation/Decrementation Cont’dCont’d

• When decrementing, the value of the When decrementing, the value of the counter is decreased by one. e.g.counter is decreased by one. e.g.– Count = Count - 1Count = Count - 1

•This means that the new value of the This means that the new value of the variable count will get the old value of count variable count will get the old value of count minus one; if count was initially 5 its new minus one; if count was initially 5 its new value will be 4value will be 4

Page 23: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ConditionalsConditionals

• Often in programming it is necessary Often in programming it is necessary to test whether a given condition has to test whether a given condition has been metbeen met– e.g. whether the value of the variable e.g. whether the value of the variable countcount is equal to 10 is equal to 10

• This is accomplished through the use This is accomplished through the use of the conditional statement, of the conditional statement, ifif

Page 24: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d

• An if statement takes the form:An if statement takes the form: if (condition)if (condition) { { do something do something } }

• For the For the do somethingdo something statement to be statement to be executed the executed the conditioncondition must evaluate to must evaluate to truetrue

Page 25: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d

• If we needed to test whether the variable If we needed to test whether the variable countcount had a value of 5, then the following had a value of 5, then the following algorithm could be used:algorithm could be used: if (count = 5)if (count = 5) { { print “Count equals 5” print “Count equals 5” } }

Page 26: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d• Similarly if we needed to test whether the Similarly if we needed to test whether the

variable count did not have a value of 5 variable count did not have a value of 5 then the following could be used:then the following could be used: if (count <> 5)if (count <> 5) { { print “Count is not equals 5” print “Count is not equals 5” } }

• Note that Note that <><> is shorthand for is shorthand for NOT (count NOT (count = 5)= 5)

Page 27: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• Other conditional operators include:Other conditional operators include:– ‘‘<‘ less than<‘ less than

•e.g. e.g. if (count < 5){ … }if (count < 5){ … }

– ‘‘>’ greater than>’ greater than•e.g.e.g. if (count > 5){ … } if (count > 5){ … }

Page 28: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d– Boolean operators includeBoolean operators include

•NOTNOT

•OROR

•ANDAND

Page 29: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• The The NOTNOT operator simply inverts a operator simply inverts a conditioncondition

• For example, if the value of the For example, if the value of the variable variable countcount is 5, then the condition is 5, then the condition count = 5count = 5 will return will return truetrue

• The condition The condition NOT (count = 5)NOT (count = 5) will will therefore return falsetherefore return false

Page 30: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d

• If a Boolean variable If a Boolean variable exitexit, for example is , for example is used, instead of writing:used, instead of writing: if (exit) if (exit) { { do something do something } }

Which executes the statement Which executes the statement do do somethingsomething if exit has a value of if exit has a value of truetrue

Page 31: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• We will write:We will write: if (NOT(exit)) if (NOT(exit)) { { do something do something } }

Which executes the statement Which executes the statement do do somethingsomething if exit has a value of if exit has a value of falsefalse

Page 32: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• The possible inputs and outputs to The possible inputs and outputs to Boolean operators are generally Boolean operators are generally illustrated in a truth tableillustrated in a truth table– Which shows all possible inputs and Which shows all possible inputs and

outputsoutputs

Page 33: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• The truth table for the NOT operator The truth table for the NOT operator is illustrated below, where is illustrated below, where AA is a is a given event:given event:

Page 34: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• The AND operator requires two The AND operator requires two eventsevents

• If both of these events are true then If both of these events are true then the Boolean condition “the Boolean condition “first eventfirst event ANDAND the the second eventsecond event” will yield ” will yield truetrue

Page 35: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d• The AND operator is often used in the The AND operator is often used in the

English language, for exampleEnglish language, for example– If it does not rain If it does not rain ANDAND I have I have

transportation then I will go to Universitytransportation then I will go to University– The two inputs to this operator are “If it The two inputs to this operator are “If it

does not rain” and “I have transportation”does not rain” and “I have transportation”– The output is true only if both of these The output is true only if both of these

inputs are trueinputs are true

Page 36: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• In an algorithm we can write the In an algorithm we can write the ANDAND operator in the following way:operator in the following way: if ((count = 5) and if ((count = 5) and (name = “BOB)) (name = “BOB)) { { do something do something } }

Page 37: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• The truth table for the AND operator The truth table for the AND operator is illustrated below:is illustrated below:

Page 38: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d• The The OROR operator is similar to the operator is similar to the ANDAND

operator in that it requires two event operator in that it requires two event as inputas input

• For For truetrue to be output, either of the to be output, either of the events must be trueevents must be true

• For example, the following English For example, the following English statement uses the statement uses the OROR operator operator

Page 39: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• If I arrive early to University If I arrive early to University OROR my my class is cancelled then I will go to class is cancelled then I will go to lunch with youlunch with you– If the individuals went to lunch together If the individuals went to lunch together

it meant that one or both of the two it meant that one or both of the two events were true, i.e. the person arrived events were true, i.e. the person arrived early or their class was cancelledearly or their class was cancelled

Page 40: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• In an algorithm we can write the In an algorithm we can write the OROR operator in the following way:operator in the following way: if ((count = 5) orif ((count = 5) or (name = “BOB)) (name = “BOB)) { { do something do something } }

Page 41: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• The truth table for the OR operator is The truth table for the OR operator is illustrated below:illustrated below:

Page 42: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• Sometimes it is required to execute Sometimes it is required to execute another statement if the tested another statement if the tested condition is not truecondition is not true

• This can be done using the This can be done using the elseelse clause, for example:clause, for example:

Page 43: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d if (count = 5)if (count = 5) { {

print “Count equals 5”print “Count equals 5” } else } else { {

print “Count does not equals 5” print “Count does not equals 5” } }

Page 44: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dConditionals Cont’dConditionals Cont’d• If statements may be nested as If statements may be nested as

many times as the programmer many times as the programmer wants, for example:wants, for example: if (faculty = “FPAS”)if (faculty = “FPAS”){{

if (class = “COMP1130”)if (class = “COMP1130”){{

print “The correct course”print “The correct course”}}

} }

Page 45: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d

• Testing more than one condition at a Testing more than one condition at a time may be achieved through a time may be achieved through a compound conditioncompound condition

• e.g. the previous nested if statement e.g. the previous nested if statement may be replaced by the compound may be replaced by the compound condition:condition:

Page 46: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

Conditionals Cont’dConditionals Cont’d if ((faculty = “FPAS”) and (class = if ((faculty = “FPAS”) and (class = “COMP1130”))“COMP1130”)){{

print “The correct course”print “The correct course”}}

Page 47: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

LoopsLoops

• Loops are used when a given event Loops are used when a given event needs to be repeatedneeds to be repeated

• There are three main types of There are three main types of looping constructs, these are:looping constructs, these are:– The The forfor loop loop

•for loops are used when the number of for loops are used when the number of iterations is known beforehanditerations is known beforehand

Page 48: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dLoopsLoops

– The The whilewhile loop loop• In while loops the condition is tested before loopingIn while loops the condition is tested before looping

– The The repeat untilrepeat until loop loop• the condition is tested after the statements in the the condition is tested after the statements in the

loop have been executedloop have been executed

• To demonstrate how these loops work, all To demonstrate how these loops work, all three loops will be used to output the three loops will be used to output the numbers 1 through 5numbers 1 through 5

Page 49: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

LoopsLoops

• The following The following forfor loop prints the loop prints the numbers from 1 to 5numbers from 1 to 5 for (i = 1 to 5)for (i = 1 to 5) { { print i print i } }

Page 50: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dLoopsLoops

• The following The following whilewhile loop prints the loop prints the numbers from 1 to 5numbers from 1 to 5 i = 1 i = 1 while (i < 6)while (i < 6) { { print i print i

i = i + 1 i = i + 1 } }

Page 51: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dLoopsLoops

• The following The following repeat untilrepeat until loop prints loop prints the numbers from 1 to 5the numbers from 1 to 5 i = 1 i = 1 repeatrepeat { { print i print i

i = i + 1 i = i + 1 } until (i = 6) } until (i = 6)

Page 52: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dLoopsLoops• Just like if statements, loops can be nestedJust like if statements, loops can be nested• For example if the user wanted to write a For example if the user wanted to write a

program to display the numbers 1 through program to display the numbers 1 through 20, with the numbers 1 – 5, 6 – 10, 11 – 15 20, with the numbers 1 – 5, 6 – 10, 11 – 15 and 16 -20 all on different lines then a and 16 -20 all on different lines then a nested loop could be usednested loop could be used– Since we need four lines of five numbers each, Since we need four lines of five numbers each,

the outer loop will loop four times, while the the outer loop will loop four times, while the inner loop will loop five timesinner loop will loop five times

Page 53: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dLoopsLoops count = 0count = 0for (i = 1 to 4)for (i = 1 to 4){{ for (j = 1 to 5) for (j = 1 to 5) { { count = count + 1 count = count + 1 print count print count } } print newline print newline} }

Page 54: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ArraysArrays

• Arrays are data structures that are Arrays are data structures that are used to represent listsused to represent lists

• Arrays typically allow the storage of Arrays typically allow the storage of data of the same type, for example a data of the same type, for example a list of numberslist of numbers

Page 55: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ArraysArrays

• Each element in the array can then Each element in the array can then be accessed using the name of the be accessed using the name of the array and the index of the elementarray and the index of the element

• For example if the name of the array For example if the name of the array presented earlier is numbers then presented earlier is numbers then numbers[1] = 1numbers[1] = 1, , numbers[2] = 7numbers[2] = 7, , and so onand so on

Page 56: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ArraysArrays

• Note that the first index in an array is Note that the first index in an array is typically 0 rather than 1typically 0 rather than 1

• Arrays make it easy to sequence Arrays make it easy to sequence through elements using a loopthrough elements using a loop

Page 57: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dArraysArrays

• For example, to print the elements in the For example, to print the elements in the numbersnumbers array a array a forfor loop could be used: loop could be used: for (i = 1 to 4) for (i = 1 to 4) { {

print numbers[i] print numbers[i] } }

• This would display the numbers 1, 7, 6 and This would display the numbers 1, 7, 6 and 88

Page 58: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ArraysArrays

• In a similar way, if an array, called In a similar way, if an array, called namesnames, contained a list of names then , contained a list of names then a loop could be used to search the a loop could be used to search the listlist

• One search algorithm that may be One search algorithm that may be employed, called linear search, is employed, called linear search, is illustrated belowillustrated below

Page 59: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dArraysArrays index = 0index = 0while (index < 5)while (index < 5){{ if (names[index] = “Sam”) if (names[index] = “Sam”) { { print “Sam was found” print “Sam was found”

} } index = index + 1 index = index + 1}}

Page 60: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ArraysArrays

• One issue with this example is that One issue with this example is that even if the item is found, the even if the item is found, the remainder of the list is still searchedremainder of the list is still searched

• This would be a waste of processing This would be a waste of processing time if we knew before hand that a time if we knew before hand that a given name only existed in the list given name only existed in the list onceonce

Page 61: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’d

ArraysArrays

• A number of methods may be used A number of methods may be used to halt the search when the given to halt the search when the given name is found including:name is found including:– a Boolean flag a Boolean flag – the counter could be set to the the counter could be set to the

terminating conditionterminating condition

Page 62: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dArraysArrays• The following example uses the The following example uses the

Boolean flag exit:Boolean flag exit:exit = falseexit = falseindex = 0index = 0while ((index < 5) and (not exit))while ((index < 5) and (not exit)){{ if (names[index] = “Sam”) if (names[index] = “Sam”) { { print “Sam was found” print “Sam was found”

exit = trueexit = true } }

index = index + 1 index = index + 1}}

Page 63: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dArraysArrays

• Remember that the loop keeps on Remember that the loop keeps on looping while the condition looping while the condition ((index ((index < 5) and (not exit))< 5) and (not exit)) is true is true

• This condition is false whenThis condition is false when– either index is equal or greater than 5either index is equal or greater than 5– Or the Boolean variable Or the Boolean variable exitexit is set to is set to

true, i.e. true, i.e. NOT(true)NOT(true) is is falsefalse

Page 64: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Computer Programming Computer Programming Cont’dCont’dArraysArrays• In the next example, the index, In the next example, the index, indexindex, ,

is set to the terminating condition:is set to the terminating condition:index = 0index = 0while (index < 5)while (index < 5){{ if (names[index] = “Sam”) if (names[index] = “Sam”) { { print “Sam was found” print “Sam was found”

index = 5 index = 5}}

index = index + 1 index = index + 1}}

Page 65: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScript ProgramsJavaScript Programs

• JavaScript programs are either JavaScript programs are either embedded in the HTML documentembedded in the HTML document

• Or, are held in a file (with a .js Or, are held in a file (with a .js extension)extension)– In XHTML 1.0 it is recommended that In XHTML 1.0 it is recommended that

scripts be held in a filescripts be held in a file

• The The SCRIPTSCRIPT element is used to element is used to specify a JavaScript programspecify a JavaScript program

Page 66: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The SCRIPT ElementThe SCRIPT Element• FunctionFunction

– A container for scriptsA container for scripts• XHTML 1.0 Example (embedded script)XHTML 1.0 Example (embedded script) <script type=“text/javascript”><script type=“text/javascript”> <!--<!-- window.document.write(“Hello web!”);window.document.write(“Hello web!”); //-->//--> </script></script>

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 67: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The SCRIPT ElementThe SCRIPT Element

• XHTML 1.0 Example (external script)XHTML 1.0 Example (external script)

<script type=“text/javascript” <script type=“text/javascript” src=“hello.js”></style>src=“hello.js”></style>

• The file hello.js containsThe file hello.js contains

window.document.write(“Hello window.document.write(“Hello web!”);web!”);

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 68: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The SCRIPT ElementThe SCRIPT Element

• Required AttributesRequired Attributes– TYPETYPE – Specifies the content type for the – Specifies the content type for the

script language, e.g. “text/javascript”script language, e.g. “text/javascript”

• Optional AttributesOptional Attributes– SRCSRC - the location of an external script - the location of an external script

•The code for The code for external scripts external scripts isis hidden from hidden from the userthe user

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 69: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScript CommentsJavaScript Comments

• If tIf the characters he characters //// appear at the appear at the beginning of a line then the rest of beginning of a line then the rest of the line is commented outthe line is commented out //// only comments one line only comments one line

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 70: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

ObjectsObjects

• JavaScript is an object-oriented languageJavaScript is an object-oriented language

• In JavaScript objects are arranged in In JavaScript objects are arranged in hierarchies and have associated with hierarchies and have associated with them:them:– PropertiesProperties– MethodsMethods– An eventsAn events

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 71: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Window ObjectThe Window Object• One of the most important JavaScript One of the most important JavaScript

objects is the objects is the windowwindow object object • The The windowwindow object object propertiesproperties include include

the:the:– menu barsmenu bars– tool barstool bars– scroll bars, andscroll bars, and– the status linethe status line

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 72: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Window Objects Cont’dThe Window Objects Cont’d

• To access a given To access a given propertyproperty the the following format is used:following format is used:

window.defaultstatus = “My Web Page”;

Object Separator Property

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 73: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

PropertiesProperties

• A property is a characteristic of an A property is a characteristic of an objectobject– e.g. length is a property of the String e.g. length is a property of the String

objectobject– And And defaultstatusdefaultstatus is a property of the is a property of the

window objectwindow object•which changes the Web browser’s status line which changes the Web browser’s status line

to “My Web Page”to “My Web Page”

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 74: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

MethodsMethods• Methods extract information from objects or Methods extract information from objects or

changes an object’s properties, e.g.changes an object’s properties, e.g.

– Which write the text “Hello” to the browser windowWhich write the text “Hello” to the browser window

window.document.write(“Hello”);

Object Method

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 75: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

MethodsMethods• A property is differentiated from a method A property is differentiated from a method

by the opening and closing parenthesesby the opening and closing parentheses

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 76: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Alert WindowThe Alert Window

• The alert window is a popup window The alert window is a popup window that alerts the user of a special that alerts the user of a special condition, e.g.condition, e.g.

– Which displays an alert window with the Which displays an alert window with the text “Hi there!” on one line and “What’s text “Hi there!” on one line and “What’s up?” on anotherup?” on another

window.alert(“Hi there!\nWhat’s up?”);

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 77: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Alert Window Cont’dThe Alert Window Cont’d

• A literal string is passed to the alert A literal string is passed to the alert methodmethod

• ‘‘\n’ \n’ (new line) (new line) characters can be used characters can be used within a literal string to within a literal string to create a create a multi-line messagemulti-line message

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 78: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Confirm WindowThe Confirm Window

• Allows one of two choices, Allows one of two choices, OkOk or or CancelCancel to a given question to a given question

• If the user selects If the user selects OkOk, a , a truetrue value is value is returned to the script, otherwise a returned to the script, otherwise a falsefalse value is returned value is returned

var choice=window.confirm("Do you wish to continue?");

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 79: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

String ConcatenationString Concatenation• Strings may be concatenated (joined) Strings may be concatenated (joined)

through the use of the concatenator through the use of the concatenator operator ‘+’, e.g.operator ‘+’, e.g.

• Which creates the string “A man Frank Which creates the string “A man Frank and his dog.” from sub strings and a and his dog.” from sub strings and a variablevariable

var name = "Frank"; var newString ="A man " + name + "and his dog.";window.document.write(newString);

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 80: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Creating VariablesCreating Variables• Variables can be created in JavaScript Variables can be created in JavaScript

through the use of the through the use of the varvar command command, , e.g.e.g.

• Which defines the variable Which defines the variable myvarmyvar and and assigns the value 10 to itassigns the value 10 to it

• Note that JavaScript variable names are Note that JavaScript variable names are case sensitivecase sensitive

var myvar = 10;

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 81: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Prompt WindowThe Prompt Window• A prompt window contains:A prompt window contains:

– a questiona question– a text field (which allows the user to a text field (which allows the user to

enter text) andenter text) and– three buttons:three buttons:

•OkOk•ClearClear•CancelCancel

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 82: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Prompt Window Cont’dThe Prompt Window Cont’d

• Pressing Pressing ClearClear clears the contents of clears the contents of the text field and sets the value to the text field and sets the value to nullnull

• The prompt window only closes if The prompt window only closes if OkOk or or CancelCancel are pressed are pressed

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 83: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Prompt Window Cont’dThe Prompt Window Cont’d

• Pressing Ok with an empty text field Pressing Ok with an empty text field returns returns nullnull

• Pressing Cancel closes the window Pressing Cancel closes the window and returns and returns nullnull

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 84: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

The Prompt Window Cont’dThe Prompt Window Cont’d

• The The prompt()prompt() method accepts two method accepts two parametersparameters– The question promptThe question prompt– The The default value of the fielddefault value of the field

var age = window.prompt(“How old are you?”, “10”);

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 85: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Arithmetic OperatorsArithmetic Operators

• Several arithmetic operators are Several arithmetic operators are available in JavaScript:available in JavaScript:

++ Increment -- Decrement- Unary minus * Multiplication/ Division % Modulus+ Addition - Subtraction= Assignment

Combined Assignment*= /= %= += -=

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 86: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Arithmetic Operators Cont’dArithmetic Operators Cont’d

• Examples of the addition and Examples of the addition and subtraction operators are given subtraction operators are given below:below:

var x = 20;var y = 10;// Additionvar result = x + y;window.document.write("<p>x + y = " + result + "</p>");

// Subtractionresult = x - y;window.document.write("<p>x - y = " + result + "</p>");

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 87: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Arithmetic Operators Cont’dArithmetic Operators Cont’d

• When the When the promptprompt statement is used statement is used to input numbers they are stored as to input numbers they are stored as stringsstrings

• In order to convert them to numbers In order to convert them to numbers the the parseInt()parseInt() and and parseFloat()parseFloat() methods are required:methods are required:

var itotal = parseInt(prompt("Enter an integer", ""));var ftotal = parseFloat(prompt("Enter a float", ""));

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 88: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Arithmetic Operators Cont’dArithmetic Operators Cont’d

• If the user does not enter an integer If the user does not enter an integer in the prompt window then in the prompt window then itotalitotal will evaluate to will evaluate to NaNNaN, not a number, not a number– This will also happen with This will also happen with ftotalftotal

• To test whether a variable contains a To test whether a variable contains a valid number use the isNaN() valid number use the isNaN() functionfunction

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 89: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

JavaScript Programs Cont’dJavaScript Programs Cont’d

• For example:For example:

if (isNaN(itotal))if (isNaN(itotal))

{{

window.alert (“Invalid number”);window.alert (“Invalid number”);

}}

Page 90: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

Arithmetic Operators Cont’dArithmetic Operators Cont’d• It is important to note that there is a known issue It is important to note that there is a known issue

with the parseInt() functionwith the parseInt() function• If you attempt to parseInt(“08”) or parseInt(“09”) If you attempt to parseInt(“08”) or parseInt(“09”)

the result returned is 0 rather than 8 and 9, the result returned is 0 rather than 8 and 9, respectivelyrespectively

• One solution to the problem is to always include One solution to the problem is to always include the base in which the resulting number is in, in the base in which the resulting number is in, in this case base 10this case base 10

• Therefore parseInt(“08”,10) = 8 and Therefore parseInt(“08”,10) = 8 and parseInt(“09”,10) = 9 as expectedparseInt(“09”,10) = 9 as expected

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 91: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• We now know enough JavaScript to We now know enough JavaScript to solve a simple problemsolve a simple problem

• The problem simply stated is:The problem simply stated is:– Write a program that accepts two Write a program that accepts two

numbers input by the user and display numbers input by the user and display their sumtheir sum

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 92: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• One version of the pseudo code for One version of the pseudo code for the solution is:the solution is:

Input number1Input number1

Input number2Input number2

result = number1 + number2result = number1 + number2

Print resultPrint result

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 93: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• Another version could be:Another version could be:

Input first numberInput first number

Input second numberInput second number

Add the first number to theAdd the first number to the

second numbersecond number

Display the resultDisplay the result

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 94: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• Utilising the first version of the Utilising the first version of the pseudo code it is clear that we need pseudo code it is clear that we need to define three variables:to define three variables:– number1number1 for the first number for the first number

• i.e. i.e. var number1 = 0var number1 = 0

– number2number2 for the second number for the second number• i.e. i.e. var number2 = 0var number2 = 0

– resultresult to hold the sum to hold the sum• i.e.i.e. var result = 0 var result = 0

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 95: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• Next, we need to input the two numbersNext, we need to input the two numbers

• This can be done using the following This can be done using the following JavaScript:JavaScript:

number1 = parseInt( prompt(“Enter first number1 = parseInt( prompt(“Enter first number”,””));number”,””));

Which prompts the user for the number Which prompts the user for the number and converts the returned string to an and converts the returned string to an integer using the function integer using the function parseInt()parseInt()

• The above is simply repeated for The above is simply repeated for number2number2

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 96: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• Next we need to add the two numbers Next we need to add the two numbers together which is done using:together which is done using:

result = number1 + number2;result = number1 + number2;• And create the message, which includes And create the message, which includes

the result, to display to the user:the result, to display to the user:var displayString = number1 +var displayString = number1 +“ + “ + number2 +“ + “ + number2 +“ = “ + result;“ = “ + result;

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 97: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

• Finally we can display the result to Finally we can display the result to the user using an alert box:the user using an alert box:

alert(displayString);alert(displayString);

• Or directly to the Web page:Or directly to the Web page:

window.document.write( window.document.write( displayString);displayString);

JavaScript Programs Cont’dJavaScript Programs Cont’d

Page 98: Web Technologies COMP6115 Session 3: Designing, Constructing, Testing and Debugging Dynamic Web Sites Dr. Paul Walcott Department of Computer Science,

ReferencesReferences

[1] Darnell, Rick, et al., “HTML4: Unleased”, Sams.net Publishing, [1] Darnell, Rick, et al., “HTML4: Unleased”, Sams.net Publishing, First Edition, 1997First Edition, 1997

[2] W3C, “HyperText Markup Language (HTML) Home Page”, 2004. [2] W3C, “HyperText Markup Language (HTML) Home Page”, 2004. Online document available atOnline document available at “http://www.w3c.org/MarkUp/”“http://www.w3c.org/MarkUp/”

[3] Deitel, H., Deitel, P., Nieto, Frank, L., Lin, Ted, M., Sadhu, [3] Deitel, H., Deitel, P., Nieto, Frank, L., Lin, Ted, M., Sadhu, Praveen, “XML: How to Program”, Prentice-Hall Inc., 2001Praveen, “XML: How to Program”, Prentice-Hall Inc., 2001

[4] Anderson-Freed, Susan, “Weaving a Website: Programming in [4] Anderson-Freed, Susan, “Weaving a Website: Programming in HTML, Javascript, Perl and Java”, Prentice Hall , 2002HTML, Javascript, Perl and Java”, Prentice Hall , 2002

[5] Koch, Stefan, “Voodoo’s Introduction to JavaScript”, 1998. [5] Koch, Stefan, “Voodoo’s Introduction to JavaScript”, 1998. Online document available at Online document available at “http://oopweb.com/JavaScript/Documents/jsintro/Volume/part1/“http://oopweb.com/JavaScript/Documents/jsintro/Volume/part1/part1.htm”part1.htm”