26
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 they have 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

lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

Embed Size (px)

Citation preview

Page 1: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

CS1046 – Lab 5Timing: 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 they have 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.

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

1

Page 2: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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). Edit the html file and add the tag below 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” for the false radio button, 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 which button was 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 selected 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 checked (i.e. either TRUE or FALSE). Thus, the variable called firstButton can only hold one of

2

Page 3: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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

Page 4: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

5. Now change the line:myBoolean = true;tomyBoolean = ”true”;

6. Save your .js file and reload your .html file7. Try clicking on your button again. It may look like it is giving the same answer but actually 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”;tomyBoolean = 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 (or relational) 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;tomyBoolean = 45 <= 48;This time 45 is less than or equal to 48, so 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 two 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

Page 5: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 === (three equal signs) means Strict Equal To so it checks both the value and the data type as well.

14. There are 8 comparison (relational) 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. 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 trueNow change that line to:myBoolean = (45 > 42) && (3 > 4);

5

Page 6: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 truetrue&&false will return falsefalse&&true will return falsefalse&&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);tomyBoolean = (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 truetrue||false will return truefalse||true will return truefalse||false will return falseChange 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

Page 7: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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);tomyBoolean = !(6>7);and save your .js file. Reload and rerun your code. 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

Page 8: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 above statement like this:rainingToday = getWeather(today); //returns true or falseif (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 in cyan), otherwise if the condition is false then the second part (the else part in green) 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

Page 9: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

PAST the IF’s curly braces (which indicates the beginning and ending of the true conditional part) and executes the line after the IF’s 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 two alert statements get executed and then the last two 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 two statements get executed, but the two 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

Page 10: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

(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

Page 11: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

going to Settings in Chrome, then More Tools, then Developer Tools to see if you can find any errors that may exist (or right click and select Inspect to see the Developer Tools Window)

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 guessfunction 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

Page 12: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 guessfunction generateTheAnswer() { theAnswer=Math.floor(Math.random() * (10-1) + 1); alert (theAnswer);}

//function to check the users guess against the answerfunction 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

Page 13: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 guessfunction generateTheAnswer() { numOfTries=0; theAnswer=Math.floor(Math.random() * (10-1) + 1); alert (theAnswer);}//function to check the user’s guess against the answerfunction 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

Page 14: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 the .html file, change this line:<h2 id="myWelcome">Colour My World</h2>To this:<h2 id="myWelcome">Your Name’s Favourite Colour is PutYourFavColor</h2>Make sure you put YOUR name and YOUR favourite colour in the line above.

5. 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(); Also change the yellow area to the colour name that is the same as your favourite colour mentioned above. For example, my favourite colour is orange, so I would put:document.getElementById('myWelcome').style.color = "orange";Type in the following code:

//change the color of the pieces of our webpagefunction changeTheColor() { var desiredColor; desiredColor=document.getElementById('colorText').value; desiredColor=desiredColor.toLowerCase(); document.getElementById('myWelcome').style.color = "PUTYOURFAVCOL"; alert(desiredColor);} //end of function

14

Page 15: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

6. 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 and displays the second heading in your favourite colour.

7. 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";}

8. 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 webpagefunction changeTheColor() { var desiredColor; desiredColor=document.getElementById('colorText').value; desiredColor=desiredColor.toLowerCase(); document.getElementById('myWelcome').style.color = "colourthatyoupicked"; 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

Page 16: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

9. 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

10. 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.

11. 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;

12. Save the .js file and try typing in the colour seafoam into the html webpage. Press the button and observe what happens.

13. Add your own case ABOVE the default: statement to check for YOUR favourite colour (or another colour if your favourite colour is one of the already used colours of green, yellow or blue). 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 or delete one of your existing break; statements and watch what happens. If you don’t want the code below to also be executed, you must remember the break; statement).

14. Finally, for each case statement, add a line that will change the background colour of the textbox to another colour in the correct family of colours (e.g. for the green case, you might set the textbox background to as the button was changed to Chartreuse). Look at the html to find the Id for the textbox. The code is EXTREMELY similar to the code for changing the button.

15. Save and test your work.

16

Page 17: lreid/cs1046/labs/lab5/lab5.docx · Web viewhowever in JavaScript, you cannot use the word AND to compare the two boolean expressions, instead you would write it like this: hasPassed=(examScore>45)

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 two 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 and the instructor can find out what colour you love!

17