Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Similar documents
CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

BEGINNER PHP Table of Contents

CMPT 100 : INTRODUCTION TO

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

ORB Education Quality Teaching Resources

Beginning HTML. The Nuts and Bolts of building Web pages.

Client Side JavaScript and AJAX

Boolean Expressions. Is Equal and Is Not Equal

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

JavaScript Basics. The Big Picture

(Refer Slide Time: 01:40)

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

Programming Lab 1 (JS Hwk 3) Due Thursday, April 28

CS 1110, LAB 1: PYTHON EXPRESSIONS.

CS Multimedia and Communications REMEMBER TO BRING YOUR MEMORY STICK TO EVERY LAB!

Project 2: After Image

Boolean Expressions. Is Equal and Is Not Equal

Programming language components

JQuery and Javascript

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

What is PHP? [1] Figure 1 [1]

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

Working with JavaScript

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

Task 1. Set up Coursework/Examination Weights

Lesson 7: If Statement and Comparison Operators

Section 1. How to use Brackets to develop JavaScript applications

c122jan2714.notebook January 27, 2014

Variables and Typing

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Lab 8 CSE 3,Fall 2017

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

JavaScript Functions, Objects and Array

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

Lesson 5: Introduction to Events

Lesson 1: Writing Your First JavaScript

Lab # 2. For today s lab:

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

CS 115 Lecture 8. Selection: the if statement. Neil Moore

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Enhancing Web Pages with JavaScript

contain a geometry package, and so on). All Java classes should belong to a package, and you specify that package by typing:

c122sep814.notebook September 08, 2014 All assignments should be sent to Backup please send a cc to this address

<script> function yourfirstfunc() { alert("hello World!") } </script>

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

1) Log on to the computer using your PU net ID and password.

Lab 1 Concert Ticket Calculator

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Programming Principles 1 (CSC131) & 2 (CSC132) Software usage guide

Text Input and Conditionals

LOOPS. Repetition using the while statement

CMSC 201 Fall 2018 Lab 04 While Loops

Advanced Web Tutorial 1 Editor Brackets / Visual Code

HTML/CSS Lesson Plans

LECTURE 08: INTRODUCTION TO HTML

[ the academy_of_code] Senior Beginners

c122mar413.notebook March 06, 2013

JAVASCRIPT - CREATING A TOC

JS Lab 1: (Due Thurs, April 27)

Student, Perfect Final Exam May 25, 2006 ID: Exam No CS-081/Vickery Page 1 of 6

Relational & Logical Operators, if and switch Statements

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Chapter 17. Fundamental Concepts Expressed in JavaScript

If Statements, For Loops, Functions

Software Design & Programming I

CoderDojo Activity Cards: The Cards (Animation2.html): How to use: Student comes to mentor, and together they choose a card to do next.

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

This tutorial will teach you about operators. Operators are symbols that are used to represent an actions used in programming.

Section 0.3 The Order of Operations

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

5. Control Statements

Agenda. My Introduction. CIS 154 Javascript Programming

COMP : Practical 8 ActionScript II: The If statement and Variables

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

INTRODUCTION (1) Recognize HTML code (2) Understand the minimum requirements inside a HTML page (3) Know what the viewer sees and the system uses

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class:

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

Civil Engineering Computation

Introduction, Notepad++, File Structure, 9 Tags, Hyperlinks 1

Adobe Business Catalyst

Getting started with social media and comping

(Python) Chapter 3: Repetition

What is XHTML? XHTML is the language used to create and organize a web page:

PYTHON YEAR 10 RESOURCE. Practical 01: Printing to the Shell KS3. Integrated Development Environment

Dynamism and Detection

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Mobile Computing Professor Pushpedra Singh Indraprasth Institute of Information Technology Delhi Andriod Development Lecture 09

Transcription:

CS1046 Lab 5 Timing: This lab should take you approximately 2 hours. Objectives: By the end of this lab you should be able to: Recognize a Boolean variable and identify the two values it can take Calculate the value in a Boolean expression Identify the 8 comparison operators Identify the 3 logical operators Label/identify the parts of an IF statement Determine when an IF statement should be required Trace a series of statements that use IF statements, including nested IF statements Write a valid IF statement Recognize the parts of a SWITCH statement Trace a switch statement Write a valid switch statement Determine when a switch statement should be used Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object One of the most basic and useful tools a carpenter has is a hammer. For a programmer, one of the most useful tools he/she has is an If statement. In this lab, you will learn how to use an If statement but first the Boolean variable must be introduced. A numeric variable can contain any number. A string variable can contain any combination of characters but a Boolean variable is different, in that it can ONLY contain one of two values: true or false. In this first exercise, we are going to use Boolean variables 1. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex1a.html Right click and view the source for this page. 2. Create a new folder called lab5. Open Notepad and then save the file (in the lab5 folder) as yourwesternuseridlab5ex1a.html (eg. jsmith2lab5ex1a.html). It is important to save the file as an.html and not.txt file. Consult Lab 1 Exercise 5 if you have trouble. 1

3. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex1.css and copy the code into your lab5 folder. Do this by using Notepad to create a new file, paste the css code in and give this new file the name: lab5ex1.css 4. Notice that the html page only has a true radio button (a radio button is a special button that only lets you select one button out of a possible group of radio buttons). Go into and edit the html and add the tags to create another radio button (copy the first radio button line and paste it immediately below that line). The line should look like this: <input class="radiobut" value="t" name="q1" type="radio">true<br/> Change the value to f and the text before the <br/> to False. Also change the name to q2. Save your html file and reload it in the browser. Watch what happens, notice that you can now click on BOTH radio buttons. This is not what we wanted. With radio buttons, if you give them ALL the same name, then the radio buttons became a group and the user can only select one of them at a time. So change the name back to q1, save your html file and make sure it lets you only select ONE of the two radio buttons. 5. Now, double check that the <script> tag is there to point to the.js file. If it is not, then add the <script> tag to your html webpage just above the </head> tag and make the script tag point to a file called booleanfun.js. Save your html file. 6. A radio button is either selected or NOT selected. We want to test our radio buttons to see if each is selected or not selected. In Notepad, create a blank file called booleanfun.js and save it to your lab5 folder. Put the following function into the js file (HINT: REMEMBER, if you copy and paste the code below, rather than typing it in yourself, you might need to retype the single and double quotes as the fancy quotes are copied rather than the plain ones and you want the plain quotes!): function whowaschecked() { var radiobuttons; var firstbutton, secondbutton; radiobuttons = document.getelementsbyname('q1'); firstbutton=radiobuttons[0].checked; alert ( First button was checked: + firstbutton); 7. Let s take a closer look at the above function. Look at the line: radiobuttons = document.getelementsbyname('q1'); Because there is more than one radio button, we store the radio buttons in an array with the name q1 (make sure you remember the s on getelementsbyname). Now look at the line: firstbutton=radiobuttons[0].checked; As discussed last week, the first position in the array is located at index 0 and as a result, our first radio button will be at position [0]. To ascertain whether the firstbutton is checked or not, we look at the checked property for the first element. Next, we store this value inside a variable called firstbutton. A radio button is always in one of two states: either it is checked or it is not 2

checked (i.e. either TRUE or FALSE). Thus, the variable called firstbutton can only hold one of two values: true or false. firstbutton is now a Boolean variable. The.checked property of a radio button is also a Boolean variable as it is either true or false and can never be any other value other than true or false. (e.g. if can NOT hold values like 1.788 or strings like Hello World ). 8. Go back into your html file; add the onclick call to call the above function from the Submit my answer Button. Save your html file and reload it. Try pressing your button after you have checked the first radio button and then when it is not checked to see the difference between the two. Make sure the alert is working properly (showing whether that first radio button was checked or not). 9. Now add the code to display if the second radio button is checked or not. The code should look almost identical to the code in Step 7 but use the variable secondbutton and remember that the second radio button will NOT be the [0]th element in the array. Remember to add the alert to see what value is in secondbutton. 10. Reload your html file and make sure that you button works properly. Congratulations, you now can: Create a group of radio buttons where only one button can be selected by giving them all the same name. List the values that a Boolean variable can accept Identify a Boolean variable Identify a Boolean property on an object such as.checked Exercise 2 Using the comparison operators and the logical operators and writing Boolean expressions 1. In this exercise, you will use the Boolean variable in more complex situations. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex1b.html Right click and view the source for this page. 2. Open Notepad and then save the html for the webpage above in a file (in the lab5 folder) as yourwesternuseridlab5ex1b.html (eg. jsmith2lab5ex1b.html). 3. Open a blank document in Notepad and save the blank file to your lab5 folder as booleanfuntwo.js and create a function called testing123 that looks like this: function testing123() { var myboolean; myboolean= true; alert(myboolean); 4. Save your.js file. Reload your.html file in the browser and click on the button on your html page and make sure the button pops up an alert that says true 3

5. Now change the line: myboolean= true; to myboolean= true ; 6. Save your.js file and reload your.html file 7. Try clicking on your button again. It may look like it is giving the same answer but in actuality the second time you clicked on the button, you were seeing a string with the value of the word: true, it was not a Boolean. A Boolean will never have quotes around it. In addition, true and false are keywords, so you cannot use them as variable names. 8. Now change the line: myboolean= true ; to myboolean= 45<38; 9. Save your.js file and then reload your html file. This time you should get a value of false. (Now myboolean is a Boolean again). It has the value false because we are saying: put the result of the expression 45 is less than 38 into the variable called myboolean. Since 45 is less than 38 is not true (i.e. it is false), it puts the value false into the variable. 45<38 is called a Boolean expression (because it results in a value of either true or false) and < is called a comparison operator. Just like x=2+3; is an arithmetic expression, the expression: x=(3>=4) is a Boolean expression. Arithmetic expressions always evaluate to numbers, while Boolean expressions always evaluate to either true or false. Change the line: myboolean= 45<38; to myboolean= 45<=48; This time 45<=48 is true, so it should return true. Sometimes brackets make it easier to read so you could put this instead: myboolean=(45<=48); 10. Remember that one equals sign (=) is the assignment operator. So age=50; means assign the value 50 to the variable age. Thus, if we want to check if two things are equal to each other (rather than less than like we did above) in a Boolean expression, we cannot use the equal sign because it already has another job, the job of assigning values to variable. So instead, we use double equals (==) to check if 2 things are equal to each other. Now change the assignment line for myboolean to: myboolean= (45==(42+3)); and check what value is returned. 11. Now change that line to: myboolean= (45!=(42+3)); and watch what happens.!= means NOT equal in JavaScript. Therefore, we are saying 45 is not equal to 42+3. That statement is false, therefore false is returned. 4

12. Now change that line to: myboolean= (45=='45'); this is checking if the value 45 is equal to the string 45. JavaScript converts the string 45 to a value, so this expression evaluates to true. 13. Now change that line to: myboolean= (45==='45'); This one should return false. That is because === (3 equal signs) means Strict Equal To so it checks both the value and the data type as well. 14. There are 8 comparison operators in JavaScript: == (equal to)!= (not equal to) === (strict equal to)!== (strict not equal to) > (greater than) < (less than) >= (greater than or equal to) <= (less than or equal to) 15. These operators can be used in a variety of situations. For instance, as shown below, you might use them to check if someone can a pass a course based on their score for the course: var haspassed, score, barforpassing; haspassed = (score >=barforpassing); 16. Sometimes you might want to compare the results of more than one Boolean expression. For example you might have a situation where a student must get more than 45% on the final exam AND more than 60% on the major assignment to pass your course. So you would have: var examscore, majorassignmentscore; var haspassed; haspassed = (examscore>45) AND (majorassignmentscore>60); however in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: haspassed=(examscore>45) && (majorassignmentscore>60); So in JavaScript && means AND 17. Go back to your code and change the line: myboolean= (45==='45'); to myboolean= (45>42) && ( 3< 4); Save your.js file and reload your html file and see what result you get. Basically we are saying: is 45 less than 42 AND is 3 less than 4. Being that both of the conditions are true, the statement evaluates to true 5

Now change that line to: myboolean= (45>42) && ( 3> 4); and see what happens. If either condition is false on either side of the &&, then the whole expression is false. So: true&&true will return true true&&false will return false false&&true will return false false&&false will return false 18. Imagine now that someone will pass your course if they get either more than 80 on the final exam OR they get more than 70 on the major assignment. Only one of those has to be true for your student to pass your course. For example: var examscore, majorassignmentscore; var haspassed; haspassed = (examscore>80) OR (majorassignmentscore>70); however in JavaScript, you cannot use the word OR to compare the two Boolean expressions, instead you would write it like this: haspassed = (examscore>45) (majorassignmentscore>60); So, in JavaScript means OR 19. Change the line: myboolean= (45>42)&&(3>4); to myboolean= (45>42) (3>4); save your.js file and reload your html file and see what you get when you press the button. In the case of an OR ( ) if either expression on either side of the is true, then the whole expression is true, so: true true will return true true false will return true false true will return true false false will return false change the line to be this now: myboolean= (5!=5) (6>7); and see what value you get, does it match what you expected? Now imagine that, if a student doesn t pass, you need to print out a warning message. To show this message you might think of something like this: If NOT (haspassed) THEN alert ( you didn t pass the course ); In JavaScript, we do not use the word NOT, instead we use the symbol! as shown below. var sendwarning; sendwarning =!(score>50); 6

Remember that NOT false is true and NOT true is false, so if we had: var b1,b2; b1 = (10==(5+5)); b2 =!b1; then b1 will hold true and b2 will hold false. 20. Change the line: myboolean = (5!=5) (6>7); to myboolean =!(6>7); and save your.js file. Before proceeding to the next step, make sure you understand what value is returned and why that is the case. 21. In programming languages: a. && (and), b. (or) c.! (not) are called logical operators. NOTE: && and must have Booleans or Boolean expressions on either side of them and! must be followed by a Boolean expression. Thus, you cannot do something like this: var x, y, z; x = 2 && 4; because 2 and 4 are not Boolean expressions or Boolean variables, however you can do this: x = 2; y = (3<1); z= (x==3) && y; 22. Boolean expressions are used extensively when writing programs, they are used when you need to write an IF statement or a loop. In the next section, we will use Boolean expression to write IF statements. Congratulations, you now can: Write a Boolean expression and assign it to a Boolean variable Identify the 8 comparison operators used when writing Boolean expression Identify the 3 logical operators ( and (&&), or ( ) and not (!) ) Evaluate a Boolean expression to decide whether it will return true or false 7

Exercise 3 Using IF statements 1. IF statements are one of the most important statements in programming and the syntax for them was purposely chosen so that they look very similar to plain English. For example, you might in English have the sentence: If it is raining then I will need to tell my daughter she needs an umbrella otherwise I will need to remind her to bring sunscreen. In JavaScript, you could write the statement like this: rainingtoday = getweather(today); //returns true or false if (rainingtoday) { alert( You need an umbrella ); //end of then (true part) else { alert( You need sunscreen ); //end of else (false - otherwise part) So an IF statement needs a Boolean condition (or variable) that evaluates to true or false (in our raining example, this was the yellow part) and if the condition is true, the first part of the IF statement will be executed (i.e., the then part), otherwise if the condition is false then the second part (the else part) will be executed. 2. Now we are going to use a Boolean variable to practice with writing If statements. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex3.html Right click and view the source for this page. 3. Open Notepad and then save the html to a file (in the lab5 folder) called yourwesternuseridlab5ex3.html (eg. jsmith2lab5ex3.html). It is important to save the file as an.html and not.txt file. Consult Lab 1 Exercise 5 if you experience difficulty. 4. Open a new file in Notepad and save this file as ifonetwothree.js in your lab5 folder. Add the following code to the.js file: function testing123() { if (1 == 2) { alert ("Math has gone crazy, now 1 equals 2"); //end of if statement alert ("at the end of testing123"); //end of function 5. Save your.js file and then reload your.html file and click on the button to see what happens. Notice that the alert statement about Math going crazy never is executed, that is because 1 does not equal 2. Thus, the condition in the IF statement is always false, so the program jumps 8

PAST the IF curly braces (which indicates the beginning and ending of the true conditional part) and executes the line after the if closing curly brace. Also notice the indentation. Indentation is extremely important for IF statements, the indentation makes it easier to understand which statements are executed when the condition is true. Change your.js function to be this now: function testing123() { if (1 == 2) { alert ("Math has gone crazy, now 1 equals 2"); alert ("i am still inside the true part of the if"); //end of if alert ("I am outside of the if"); alert ("at the end of testing123"); // end of function 6. Save your.js file, reload your.html file and watch what happens when you click your button. 7. Now change the if (1==2) to if (1<= 2) and save your.js file and reload your html and watch what happens when you click on the button. Now because the condition is true, the first 2 alert statements get executed and then the last 2 alert statements get executed regardless of the condition. 8. Now change your function to this: function testing123() { if (1 <= 2) { alert ("Whew 1 is still less than 2"); alert ("i am still inside the true part of the if"); //end of true part else { alert ("Oh no, this is false"); alert ("I am still inside the if statement, but now in the false part of it"); //end of false (else) part alert ("I am outside of the if"); alert ("at the end of testing123"); // end of function 9. Save your.js file and reload, click on the button and watch what happens. Notice that again the first 2 statements get executed, but the 2 alert statements in the else block are skipped over. This is because this code inside the curly braces { and immediately after the else are only executed when the condition is false. Think of a condition that would return false and put it in the brackets () after the if, i.e. right here: if (1 <= 2) (change this to a expression that evaluates to false). Notice again that the else part of the if statement (the part in curly braces after the else keyword), is indented also. Make sure you ALWAYS indent the true part of your IF statement and the false part (the else part) of your IF statement. Indentation makes IF statements easier to read and understand for programmers 9

(although the computer doesn t really care if you indent or not). Then save your.js file and make sure that only the else statements are executed and not the first part (i.e., the statements which are within the curly braces for the true). You don t HAVE to have an else on your IF statements, but sometimes you might need one. Congratulations, you now can: Create a syntactically correct IF statement Determine which part of an IF statement will be executed based on the Boolean condition Identify the statements that will be executed if the condition is true Identify the statements that will be executed if the condition is false (the else part) Identify the end of the IF statement Exercise 4 Using nested if statements and using the if statement in a real world scenario Making a High Low Game 1. Now we are going to use a Boolean variable in a real world scenario. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex4.html Right click and view the source for this page. 2. Open Notepad and then save the html for the above in a file (in the lab5 folder) as yourwesternuseridlab5ex4.html (eg. jsmith2lab5ex4.html). 3. Open the file: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex4.css and save it as lab5ex4.css to your lab5 folder. 4. Load the.html file into the Chrome browser and see what the page looks like. We are going to write the code that will generate a random number between 1 and 10 and then allow the user to enter guesses until the user gets the correct answer. 5. Open Notepad and create a new file in the folder lab5 called highlowgame.js 6. First we need to generate a random number when the webpage is loaded. The original random number we generate has to be available for the entire time the page is displayed so we will make it a global variable. At the top of your.js file, NOT in a function, declare a variable called theanswer 7. Create a function called generatetheanswer() that generates a random number between 1 and 10 and stores the number in the variable called theanswer. Just for testing purposes, right after you generate the random number, put an alert statement that shows what is stored in theanswer. Save your.js file. 8. Next, in your.html file, we are going to add a call to the function generatetheanswer() WHEN the webpage loads. To do this, go to the <body> tag and change it so it looks like this: <body onload="generatetheanswer();"> 9. Now save your.html file and reload it. Make sure you can see the random number that your page is generating. Make sure it is a number between 1 and 10. If nothing is happening, try 10

going to Settings in Chrome, then More Tools, then Developer Tools to see if you can find any errors that may exist. 10. If you are still experiencing problems, edit your.js file so that it looks similar to this: var theanswer; // generate the number that the user must guess function generatetheanswer() { theanswer=math.floor(math.random() * (10-1) + 1); alert (theanswer); 11. Now we are going to write the code to check the user s guess. We will make another function called checktheguess(). Inside this function we will first declare a variable called theguess and assign it to the value of the element with the ID of guess (this is the textbox). This will put the value the user typed into the textbox, into the variable theguess. Put an alert temporarily to see if you are getting the guess correctly. Your code should look like this: function checktheguess() { var theguess; //holds users guess theguess=document.getelementbyid('guess').value*1; alert(theguess); 12. Now go back to your html code and add the onclick() to the <button> tag so that when the user clicks the button, it calls the function checktheguess(); Save your html file and make sure it works (make sure the alert for the answer is popping up and the alert for the user s guess in the text box is popping up) 13. Now go back to your.js code and remove the alert that is displaying the guess. Now we are going to start using IF statements. Firstly we will add an IF statement to ascertain whether the guess is too large, and if so, we will alert the user. Your function should now look like this: function checktheguess() { var theguess; //holds users guess theguess=document.getelementbyid('guess').value*1; if (theguess > theanswer) { alert( Your guess was too high. ); 14. Now write the IF statement that comes after the first one that will check if the users guess was too low. Save your.js file 15. Reload your html file and see if the check for high and low is working. After you have that working, add a third if statement that will check if theguess was equal to theanswer and if so, print out a message (alert) like Congratulations, you win! 11

16. Save your.js file and make sure your game works. Your.js code should look similar to this: var theanswer; // generate the number that the user must guess function generatetheanswer() { theanswer=math.floor(math.random() * (10-1) + 1); alert (theanswer); //function to check the users guess against the answer function checktheguess() { var theguess; //holds users guess theguess=document.getelementbyid('guess').value*1; if (theguess > theanswer) { alert( Your guess was too high. ); if (theguess < theanswer) { alter( Your guess was too low. ); if (theguess == theanswer) { alter( Congrats, you win. ); 17. The only problem now is that we are letting the user have lots of guesses. Maybe we only want the user to get 3 tries to get the correct answer. Declare another GLOBAL variable called numoftries (since we do not want it reset every time the user presses the button) at the top of the.js file. In the generatetheanswer() function, set the numoftries to zero as the user hasn t guessed when the page loads. In the IF statement for too high and the IF statement for too low, add one to the variable, because if these statements execute, then the user has used a turn. The code for your ifs should look similar to this: if (theguess > theanswer) { numoftries = numoftries+1; alert ("Your guess was too high"); 18. There are many ways we could check to see if the user has run out of guesses, here is one way you could handle it: if ((theguess == theanswer) && (numoftries<3)) { alert ("You Win"); 12

19. Save your.js file and reload your html file and make sure the user has to guess the number in 3 or less tries. 20. The only problem with our program now is that if the user guesses 4 or 5 times, it will still say Too High or Too Low. Maybe at this point, we just want to tell them that they cannot guess anymore. In order to do that, we are going to use a NESTED IF STATEMENT (i.e., an if statement inside of another if statement). Before we do anything in the function, we are going to use an IF statement to see if we still have guesses available, if we do then we will do the other ifs, otherwise we will output a message telling the user that he/she is out of guesses. The code will look like this (the red code is the outer if and the blue is the inner if): var theanswer; var numoftries; // generate the number that the user must guess function generatetheanswer() { numoftries=0; theanswer=math.floor(math.random() * (10-1) + 1); alert (theanswer); //function to check the user s guess against the answer function checktheguess() { var theguess; //holds users guess theguess=document.getelementbyid('guess').value * 1; if (numoftries < 3) { //allow them to keep guessing as they still have tries if (theguess > theanswer) { numoftries=numoftries+1; alert ("Too High"); //end of first INNER if if (theguess < theanswer) { numoftries=numoftries+1; alert ("Too Low"); //end of second INNER if if (theguess == theanswer) { alert ("You Win"); //end of third INNER if //end of true part for OUTER if else { alert("sorry, you have run out of tries."); //end of else for OUTER if //end of function 21. See if you can now add the code to let the user know the number of guesses he/she has left BEFORE he/she runs out of the 3 guesses. 13

22. Save the.js file and.html file Congratulations, you now can: Write a nested if statement Create a very simple game that runs in a browser! Exercise 5 Using Switch statements 1. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex5.html View the source and copy it, open Notepad and then save the.html (in the lab5 folder) as yourwesternuseridlab5ex5.html (eg. jsmith2lab5ex5.html). 2. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab5/lab5ex5.css and copy that code into your lab5 folder. Use Notepad to create a new file, paste the css code in and give this new file the name: lab5ex5.css 3. Reload the html page in Chrome. In this exercise, we are going to write code that will allow us to change the colours of our webpage based on a colour entered into the textbox by the user. 4. In Notepad, create a new file and save it with the name colourmypage.js in your lab5 folder. We could choose to change the colours just using IF statement. Let s do that first. Create a function called changethecolor(). In the function, the first thing we are going to do is check what colour the user typed in and change it to lowercase using a predefined function called tolowercase(); Type in the following code: //change the color of the pieces of our webpage function changethecolor() { var desiredcolor; desiredcolor=document.getelementbyid('colortext').value; desiredcolor=desiredcolor.tolowercase(); alert(desiredcolor); //end of function 5. Save your file, reload your html file, type a colour (with some upper case letters in it) into the textbox, click on the button and make sure the function outputs the colour name in lowercase. 14

6. Replace the line: alert(desiredcolor); with the lines: if (desiredcolor=='green') { document.body.style.backgroundcolor="lightgreen"; document.getelementbyid("mybutton").style.backgroundcolor="darkolivegreen"; else if (desiredcolor == 'yellow') { document.body.style.backgroundcolor="gold"; document.getelementbyid("mybutton").style.backgroundcolor="palegoldenrod"; 7. Save your.js file and reload your.html file again. Try typing yellow into the textbox and watch what happens. We could continue using IF statements to do this but JavaScript provides us with an alternative statement to perform this type of checking. This statement is called a SWITCH statement. Switch statements are ideal when we need to check the value of a single variable, in our case, desiredcolor, to see if it is equal to a value, in our case a colour name. A switch statement starts with a variable called the switch value and checks each case to see if the variable equals this value. If it finds a case that DOES equal the value, then it executes the switch code up until it hits a break statement. Once it hits a break statement, it jumps to the end of the switch statement. Change your function, so that it looks like this now: //change the color of the pieces of our webpage function changethecolor() { var desiredcolor; desiredcolor=document.getelementbyid('colortext').value; desiredcolor=desiredcolor.tolowercase(); switch (desiredcolor) { case green : document.body.style.backgroundcolor="lightgreen"; document.getelementbyid("mybutton").style.backgroundcolor="darkolivegreen"; break; case yellow : document.body.style.backgroundcolor="gold"; document.getelementbyid("mybutton").style.backgroundcolor="palegoldenrod"; break; //end of switch statement //end of function 15

8. Save your.js file and reload your html file and test it. NOTE a switch statement is only useful if you are just testing ONE variable (thus, a condition like if((grade>50) && (assignment1<80)) could not be translated into a switch statement because you need to check both the grade and the assignment1 variables). NOTE the general syntax for a JavaScript switch statement is: switch (variabletobetested) { case value1: statement(s); break; case value2: statement(s); break; case // end of switch 9. Now add another case to check to see if desiredcolor is blue. If so, change the body background to CornflowerBlue and the button background to Navy. Save your.js file and make sure the webpage still works when the user enters blue. 10. If the user enters a colour we don t know or leaves the textbox empty, we can still use the switch statement to catch that by using the default statement. Right before the line: //end of switch statement add the following lines: default: document.body.style.backgroundcolor="white"; alert ("Sometimes I don't know my favourite colour either!"); break; 11. Save the.js file and try typing in the colour seafoam into the html webpage. Press the button and observe what happens. 12. Add a case ABOVE the default: statement to check for YOUR favourite colour and then set the page (body) background and button background to shades of those colours using this webpage to find some shades you like: http://www.w3schools.com/colors/colors_names.asp. Do not forget to include the break; statement (try intentionally forgetting it and watch what happens, if you don t want the default executed, you need the break statement). 13. Finally, for each case statement, add a line that will change the background colour of the textbox to the same colour as the button was changed to. Look at the html to find the Id for the textbox. The code is EXTREMELY similar to the code for changing the button. 14. Save and test your work. 16

Congratulations, now you can: Identify the parts of a switch statement (the switch variable, the opening of the statement the opening curly brace, the cases, the breaks to end the cases, the default and the closing curly brace for the switch statement) Write a case statement for a switch variable Write a default and some statements, for actions to happen when nothing matches the switch variable Identify the flow of control if the programmer forgets to include the break at the end of a case in a switch statement HAND THIS WORK INTO OWL IN ORDER TO GET YOUR LAB MARK. 1. Go into owl, under assignments and for the Lab5 Activities assignment, submit the 2 files you created for Exercise 5 the file youruseridlab5ex5.html and the file colourmypage.js so that we can check that your code is working properly. 17