mark dixon, socce soft 131page 1 05 – constants and variables

44
Mark Dixon, SoCCE SOFT 131 Page 1 05 – Constants and Variables

Post on 21-Dec-2015

224 views

Category:

Documents


1 download

TRANSCRIPT

Mark Dixon, SoCCE SOFT 131 Page 1

05 – Constants and Variables

Mark Dixon, SoCCE SOFT 131 Page 2

Admin: Test (next week)

• In class test– teaching week 6 (university week 14)

• 50 mins

• multiple choice/short answer (5 - 6 words max)

• 25% of coursework mark

Mark Dixon, SoCCE SOFT 131 Page 3

Questions: Conditional Execution

• What is the result of (txtFah.Value is 50):(txtFah.Value >= 40)

• What will txtTax be after the following code has executed (txtSalary.Value is 4589): If txtSalary.Value < 5035 Then txtTax.Value = 0 Else txtTax.Value = txtSalary.Value * 0.20 End If

true

0

Mark Dixon, SoCCE SOFT 131 Page 4

Session Aims & Objectives• Aims

– Introduce you to (invisible) data storage concepts, i.e. constants and variables

• Objectives,by end of this week’s sessions, you should be able to:

– declare and use constants– declare a variable– assign a value to a variable,

• using combination of literal values, operators, functions, and identifiers

– Determine whether a variable or procedure is in or out of scope at a given point in a piece of code

– Select a variable’s scope in your own program

Mark Dixon, SoCCE SOFT 131 Page 5

Absolute Positioning

• change properties – change position

picBall.style.pixeltop

picBall.style.pixelleft

picBall.width

picBall.height

document.body.clientwidth

Mark Dixon, SoCCE SOFT 131 Page 6

Example: Space v1<html> <head> <title>Space Explorer</title> <script language=vbscript> Sub window_OnLoad() Randomize imgAstr.style.pixeltop = 100 End Sub Sub btnRand_OnClick() imgAstr.style.pixelleft = Rnd() * 300 End Sub </script> </head>

<body> <input id=btnRand type=button value=Random /> <img id=imgAstr src="ASTR.gif" style="position: absolute;" /> </body></html>

Shuffles random number generator

Picks random number between 0 and 1

Mark Dixon, SoCCE SOFT 131 Page 7

Example: Moon Orbit – AnalysisSPECIFICATION

• User Requirements – need to keep children occupied/entertained, while

learning about the moon's orbit

• Software Requirements– Functional:

–Orbit of moon around earth should be animated–Children should be able to control speed and

direction– Non-functional

should be easy and fun to use

Mark Dixon, SoCCE SOFT 131 Page 8

Problem solving: Pseudo-code• To solve problem

– think about how you would solve it manually (without computer)

– think of steps you would take

• Moon position– increase angle– move moon

• horizontal position• vertical position

• Convert to code

1

2

3

Mark Dixon, SoCCE SOFT 131 Page 9

Trigonometry: Triangles

150

Sin(ang) * H

Cos(ang) * H

angle (ang)

hypotenuse (H)

opposite (O)

adjacent (A)

Mark Dixon, SoCCE SOFT 131 Page 10

Example: Moon Orbit v1<html> <head> <title>Moon orbit</title> <script language=vbscript>

Sub Window_OnLoad() imgMoon.Style.PixelLeft = imgEarth.style.pixelleft imgMoon.Style.PixelTop = imgEarth.style.pixeltop + 150 window.SetInterval "MoonRotate", 50 End Sub

Sub MoonRotate() parAngle.InnerText = parAngle.InnerText + 0.025 imgMoon.Style.PixelLeft = imgEarth.style.PixelLeft + (Sin(parAngle.InnerText) * 150) imgMoon.Style.PixelTop = imgEarth.style.PixelTop + (Cos(parAngle.InnerText) * 150) End Sub </script> </head>

<body bgcolor=black> <p id=parAngle style="color: Yellow">0</p> <img id=imgEarth style="position: absolute; left: 200; top: 200;" src=Earth.gif> <img id=imgMoon style="position: absolute;" src=Moon.gif> </body></html>

123

Mark Dixon, SoCCE SOFT 131 Page 11

Problem: Magic Numbers• Some numbers

represent thesame thing– e.g. the orbit

<html> <head> <title>Moon orbit</title> <script language=vbscript>

Sub Window_OnLoad() imgMoon.Style.PixelLeft = imgEarth.style.pixelleft imgMoon.Style.PixelTop = imgEarth.style.pixeltop + 150 window.SetInterval "MoonRotate", 50 End Sub

Sub MoonRotate() parAngle.InnerText = parAngle.InnerText + 0.025 imgMoon.Style.PixelLeft = imgEarth.style.PixelLeft + (Sin(parAngle.InnerText) * 150) imgMoon.Style.PixelTop = imgEarth.style.PixelTop + (Cos(parAngle.InnerText) * 150) End Sub </script> </head>

<body bgcolor=black> <p id=parAngle style="color: Yellow">0</p> <img id=imgEarth style="position: absolute; left: 200; top: 200;" src=Earth.gif> <img id=imgMoon style="position: absolute;" src=Moon.gif> </body></html>

• changes– take time– could make

mistake

Mark Dixon, SoCCE SOFT 131 Page 12

• name used to represent literal value

Const name = expression

• example:Const last = 5

• useful for removing 'magic numbers'

• value can’t be changedlast = 7

Constants (what and how)

Mark Dixon, SoCCE SOFT 131 Page 13

Example: Moon Orbit v1.1<html> <head> <title>Moon orbit</title> <script language=vbscript> Const orbit = 150

Sub Window_OnLoad() imgMoon.Style.PixelLeft = imgEarth.style.pixelleft imgMoon.Style.PixelTop = imgEarth.style.pixeltop + orbit window.SetInterval "MoonRotate", 50 End Sub Sub MoonRotate() parAngle.InnerText = parAngle.InnerText + 0.025 imgMoon.Style.PixelLeft = imgEarth.style.PixelLeft + (Sin(parAngle.InnerText) * orbit) imgMoon.Style.PixelTop = imgEarth.style.PixelTop + (Cos(parAngle.InnerText) * orbit) End Sub </script> </head> <body bgcolor=black> <p id=parAngle style="color: Yellow">0</p> <img id=imgEarth style="position: absolute; left: 200; top: 200;" src=Earth.gif> <img id=imgMoon style="position: absolute;" src=Moon.gif> </body></html>

• only need to changeconstant declaration

Declarationof Constant

Use ofConstant

quicker fewer mistakes meaningful

Mark Dixon, SoCCE SOFT 131 Page 14

Constants: missing =<html> <head> <title>Errors with Constants</title> <script language=vbscript> Const hi = 4 Const low parC.InnerText = "Hello" parC.InnerText = 23 parC.InnerText = hi hi = 6 </script> </head> <body> <p id=parC></p> </body></html> • must give constant a value

Mark Dixon, SoCCE SOFT 131 Page 15

<html> <head> <title>Errors with Constants</title> <script language=vbscript> Const hi = 4 Const low = 1 parC.InnerText = "Hello" parC.InnerText = 23 parC.InnerText = hi hi = 6 </script> </head> <body> <p id=parC></p> </body></html>

Constants: Illegal assignment

• cannot change value of constant

Mark Dixon, SoCCE SOFT 131 Page 16

Questions: Constants

• Consider the following code: Const Lives = 5 Const Players Lives = 7 document.title = Lives

• How many constants are in it?

• Which lines are OK?

• Write a line of code that declares a constant for pi (3.141592)

2

first and last

Const pi = 3.141592

Mark Dixon, SoCCE SOFT 131 Page 17

<html> <head> <title>Moon orbit</title> <script language=vbscript> Const orbit = 150 Sub Window_OnLoad() imgMoon.Style.PixelLeft = imgEarth.style.pixelleft imgMoon.Style.PixelTop = imgEarth.style.pixeltop + orbit window.SetInterval "MoonRotate", 50 End Sub Sub MoonRotate() parAngle.InnerText = parAngle.InnerText + 0.025 imgMoon.Style.PixelLeft = imgEarth.style.PixelLeft + (Sin(parAngle.InnerText) * orbit) imgMoon.Style.PixelTop = imgEarth.style.PixelTop + (Cos(parAngle.InnerText) * orbit) End Sub </script> </head> <body bgcolor=black> <p id=parAngle style="color: Yellow">0</p> <img id=imgEarth style="position: absolute; left: 200; top: 200;" src=Earth.gif> <img id=imgMoon style="position: absolute;" src=Moon.gif> </body></html>

Problem: Intermediate Results

• Intermediate result (angle)stored in object property

(parAngle.InnerText)

– verbose

– visible

– takes lot of memory

Mark Dixon, SoCCE SOFT 131 Page 18

Variables (why?)• Variables useful for:

– reducing memory use

– speed up execution

– storing information you don't want user to see

– storing intermediate results of calculations temporarily:

• makes code easier to understand, &

• prevents need to re-calculate

– making code easier to read (short variable name instead of long object.property names)

Mark Dixon, SoCCE SOFT 131 Page 19

Variables (what)• Variables have

– Identifier (name) – you choose this, used to refer to (reference) variable

– Value – you set/change this

23xName/Identifier

Value Memory

Mark Dixon, SoCCE SOFT 131 Page 20

Variable declaration (how)• Variables must be declared,

using the following syntax (grammar):

Dim identifier

e.g. Dim weight Dim x Dim s Dim year

represents the name of the variable

Mark Dixon, SoCCE SOFT 131 Page 21

Variable assignment (how)• Variables are assigned values,

using the following syntax:

identifier = expression

e.g. x = 5 weight = 109.45name = "Bob" s = "Hello "

Note: the data flows backwards (from right to left)

Mark Dixon, SoCCE SOFT 131 Page 22

Variables: Numeric Data

Mark Dixon, SoCCE SOFT 131 Page 23

Variables: String Data

Mark Dixon, SoCCE SOFT 131 Page 24

<html> <head> <title>Moon orbit</title> <script language=vbscript> Const orbit = 150 Dim ang Sub Window_OnLoad() imgMoon.Style.PixelLeft = imgEarth.style.pixelleft imgMoon.Style.PixelTop = imgEarth.style.pixeltop + orbit window.SetInterval "MoonRotate", 50 ang = 0 End Sub Sub MoonRotate() ang = ang + 0.025 imgMoon.Style.PixelLeft = imgEarth.style.PixelLeft + (Sin(ang) * orbit) imgMoon.Style.PixelTop = imgEarth.style.PixelTop + (Cos(ang) * orbit) End Sub </script> </head> <body bgcolor=black> <img id=imgEarth style="position: absolute; left: 200; top: 200;" src=Earth.gif> <img id=imgMoon style="position: absolute;" src=Moon.gif> </body></html>

Example: Moon Orbit v1.2

Declarationof Variable

Use ofVariable

shorter code invisible to user memory efficient faster execution

initial value

change value

Mark Dixon, SoCCE SOFT 131 Page 25

Example: Moon Orbit v1.3

• How can we change the speed and direction of the moon?

Mark Dixon, SoCCE SOFT 131 Page 26

Option Explicit

• Must be first line of script

• Useful to force explicit variable declaration:

• Undeclared variables produce error message:

<script language=vbscript> Option Explicit Dim length length = 6 age = 5</script>

Mark Dixon, SoCCE SOFT 131 Page 27

Questions: Variable declaration

• Write a line of code that:

– Declares a variable called x

– Declares a variable called y

– Declares a variable called surname

– Declares a variable called age

Dim x

Dim y

Dim surname

Dim age

Mark Dixon, SoCCE SOFT 131 Page 28

Questions: Variable assignment

• Write a line of code that:

– Assigns the value of 23 to the variable y

– Assigns the value of 14.6 to the variable x

– Assigns the value of ‘John’ to the variable surname

y = 23

x = 14.6

surname = "John"

Mark Dixon, SoCCE SOFT 131 Page 29

Questions: Variable assignment 2• Write a line of code that:

– Increases the value of x by 2.89

– Decreases the value of z by y

– Divides Km by 1.6 and puts the result in Miles

– Joins two strings Surname and Forenames together, putting the result in LongName

x = x + 2.89

z = z - y

Miles = Km / 1.6

LongName = Surname & Forenames

Mark Dixon, SoCCE SOFT 131 Page 30

Example: GuessNum – AnalysisSPECIFICATION

• User Requirements – need to keep children occupied/entertained, while

learning about maths

• Software Requirements– Functional:

–computer picks a number between 0 and 10–user enters a number–compare numbers and display appropriate

message– Non-functional

should be easy and fun to use

Mark Dixon, SoCCE SOFT 131 Page 31

Example: GuessNum - Code <head> <script language="VBScript"> Option Explicit Dim GuessNum

Sub window_OnLoad() Randomize GuessNum = Int(Rnd() * 10) lblResult.innerText = GuessNum End Sub

Sub btnGuess_OnClick() If CInt(txtGuessNum.Value) = GuessNum Then lblResult.InnerText = "Correct" Else lblResult.InnerText = "Wrong, please try again" End If End Sub </script> </head> <body> <p>I am thinking of a number between 0 and 10 <input type=text id=txtGuessNum> <input type=button id=btnGuess value=Guess> <p>Please guess the number <p id=lblResult> </body>

GenerateRandomNumberbetween 0 and 10

Temporary line(helps us test)

Mark Dixon, SoCCE SOFT 131 Page 32

Variables: ErrorsOption ExplicitDim z

Sub Window_OnClick()Dim sDim xDim x y = 5 z = 5End Sub

OK, explicit variable declarationOK

OKOKOK Duplicate definition error. Variable not defined error.OK, as z is page level

Mark Dixon, SoCCE SOFT 131 Page 33

Variable Scope (what)

• Scope – accessibility/visibility

– Local (declared within procedure)

– Page (general declarations)

Mark Dixon, SoCCE SOFT 131 Page 34

Variable Scope (How)

• Page variables– general

declarations (top)

• Local variables:– in procedures

Option ExplicitDim mv

Sub btnCalc_OnClick()Dim lv1 ...End Sub

Sub btnAdd_OnClick()Dim lv2 ...End Sub

Mark Dixon, SoCCE SOFT 131 Page 35

Variables: Scope (How)

Mark Dixon, SoCCE SOFT 131 Page 36

Variable Scope (why)• In short – Robustness of code/software

– Protection from accidental outside interference

• One of many responses to code that is– Difficult to maintain, and– Unreliable– House of cards phenomenon

• Prevent:– Uncontrolled and ad hoc interactions between code

• Always define things at lowest level needed

Mark Dixon, SoCCE SOFT 131 Page 37

Variable Scope Errors

• Spot the error in the following: Option Explicit

Sub btnCalc_OnClick()

Dim x

x = 0

lblTotal.InnerText = "£" & x

End Sub

Sub btnQuit_OnClick()

x = 0

lblTotal.InnerText = "£" & x

End Sub

Variable not defined error

Mark Dixon, SoCCE SOFT 131 Page 38

Example: Ball Char (v2.5)<html> <head> <title>Test</title> <script language="VBScript"> Sub Window_OnLoad() Window.SetInterval "MoveBallRight", 50 End Sub Sub MoveBallRight() If (picBall.hspace + 5) < (document.body.clientwidth - picBall.Width) Then picBall.hspace = picBall.hspace + 5 Else Window.SetInterval "MoveBallLeft", 50 End If End Sub Sub MoveBallLeft() If (picBall.hspace) > 0 Then picBall.hspace = picBall.hspace - 5 Else Window.SetInterval "MoveBallRight", 50 End If End Sub </script> </head> <body bgcolor="#00ff00"> <p><img id=picBall src="BallChar.jpg" hspace=0 vspace=11></p> </body></html>

Mark Dixon, SoCCE SOFT 131 Page 39

Example: Ball Char (v3)<html> <head> <title></title> <script language=VBScript> Dim hInc

Sub window_OnLoad() window.setInterval "BallMove", 50 hInc = 5 End Sub Sub BallMove() Dim nxt nxt = imgBall.style.pixelleft + hInc If nxt >= 0 And nxt + imgBall.width =< document.body.clientwidth Then imgBall.style.pixelleft = nxt Else hInc = -hInc End If End Sub </script> </head> <body style="margin-left: 0"> <img id=imgBall src="BALLCHAR.gif" style="position: absolute" /> </body></html>

Using variables: shorter code invisible to user memory efficient faster execution

page variable

local variable

Mark Dixon, SoCCE SOFT 131 Page 40

Question: Variable Scope• Will this compile?

Option ExplicitDim vDim x … Sub Window_OnLoad() Dim z x = 23 y = "there" z = 12 end

Sub btnTest_OnClick() Dim y y = "hello" x = 67 z = 53 End Sub

Is x in scope?Is y in scope?Is z in scope?

Is y in scope?Is x in scope?Is z in scope?

YesNoYes

YesYesNo

Mark Dixon, SoCCE SOFT 131 Page 41

Tutorial Exercises: Space• LEARNING OBJECTIVE:

use properties to perform change position of objects

• Task 1: Get Space example working. The code is provided on the slides.

• Task 2: Add an image of a spacecraft to your page. The image is in the web-site's resources.

• Task 3: Add a button that positions the spacecraft at the bottom of the screen.

• Task 4: Add a button that positions the spacecraft to the left of the asteroid.

• Task 5: Add a button that positions the spacecraft on the right of the asteroid.

Mark Dixon, SoCCE SOFT 131 Page 42

Tutorial Exercises: Moon Orbit• LEARNING OBJECTIVE:

use constants and variables to simplify and make code more dynamic

• Task 1: Get Moon Orbit examples working (v1 to v1.2). The code is provided on the slides.

• Task 2: Modify your page to allow the user to stop speed up and change the moon's direction (v1.3). Use the existing code as inspiration.

• Task 3: Modify your page so that it makes a water noise when the mouse moves over the Earth, and the ohh noise over the moon. Use code from previous lectures as inspiration.

• Task 4: Modify your page so that the diameter and mass of the Moon are displayed when the mouse moves over it. Do the same for the Earth. Go on-line to find the diameter and mass information.

Mark Dixon, SoCCE SOFT 131 Page 43

Tutorial Exercises: Guess Num• LEARNING OBJECTIVE:

use constants and variables to simplify and make code more dynamic

• Task 1: Get GuessNum example working.• Task 2: Modify GuessNum to tell the user whether their

incorrect guess was higher of lower than the correct number.• Task 3: Modify GuessNum to only allow 5 attempts before

picking a new number.

Mark Dixon, SoCCE SOFT 131 Page 44

Tutorial Exercises: Ball Char• LEARNING OBJECTIVE:

use constants and variables to simplify and make code more dynamic

• Task 1: Get the Ball Char (v3) example working.• Task 2: Add sound to the Ball Char (v3) example.• Task 3: Get the Ball Char moving diagonally, bouncing off all

four sides of the window.• Task 4: Modify your page so that it allows the user to control

how fast the ball character moves.