Javascript_String 2
CS 1150 JavaScript Programming (total points:40)
NOTE: Two-week lab!
Last updated timestamp 1424708452
What To Turn In: first_last_javascript_lab.zip
[example: if your name was Dikembe Mutombo Mpolondo Mukamba Jean-Jacques Wamutombo (like the NBA player), you would name the file dikembe_wamutombo_javascript_lab.zip]
The zip file should contain:
· part1.html
· part2.html
· part3.html
· part4.html
· part5a.html
· part5b.html
· (optional): partOXC1.html
· (optional): partOXC2.html
· first_last_javascript_lab.doc (Simply rename this file, the one you are reading right now.)
Materials needed: text editor (Notepad or Notepad ++) ; web browser, preferably Chrome
Introduction:
In this lab, you will be working with JavaScript code. It is a programming language designed for use with web browsers and web sites. Normally, it is simply embedded in the middle of the HTML code of a web page.
You will need a PLAIN TEXT editor (I recommend Notepad++) for this assignment.
DO NOT USE MICROSOFT WORD. Attempting to do this assignment in Microsoft Word is a recipe for disaster.
Wikipedia article on JavaScript: http://en.wikipedia.org/wiki/JavaScript
Useful JavaScript Tutorial: http://www.w3schools.com/js/
Example Javascript +HTML code.
The part that is actually JavaScript is in bold. The rest is the HTML “wrapper.”
<html>
<head>
<!-- This is how to do comments in the HTML. -->
<script language="javaScript">
/*
This is one way to make comments.
Everything between the stars is visible only to people looking at the JavaScript code. It’s like a secret message.
*/
//Another way to do JS Comments. This line is invisible!
//The actual JavaScript is inside an HTML “wrapper”.
// everything from <script language="javaScript">
// ...to <script>.
document.write("Hello World");
alert("Hello World");
</script>
<!-- External Javascript Function -->
<script language="JavaScript" src="javascript.js" type="text/javascript"/>
</head>
<body>
</body>
</html>
Exercise 1: Hello World. (4 points)
1. Open Notepad and type, or copy/paste, the following javascript program. Save it with the name “part1.html.”
<html>
<head>
<!-- Internal Javascript Function -->
<script language="javaScript">
document.write("Hello World");
alert("Hello World");
</script>
<!-- External Javascript Function -->
<script language="JavaScript" src="javascript.js" type="text/javascript"/>
</head>
<body>
</body>
</html>
2. Once you have saved the file in a place you can find it, find it and double-click the file. Your web browser should open and the words “Hello World” should be displayed in the window and in a separate message box. You may have to click “allow” for the application to run.
3. With your browser window remaining open, open your text file containing the Javascript code. (open the text file in a text editor like notepad or notepad++) Configure your windows so that they are side-by-side, as shown on the next page. You may need to click “OK” on the message box before performing this step.
Example below. Every time you save, you can just reload the web page.
This configuration will allow you to modify your code and run the updated version very easily, without the need to close and re-open windows as you switch from editing the code to testing the code. You should leave your windows configured this way while completing the rest of this lab exercise.
4. Within the text editor, change the words “Hello World” to “Hello, [your name]” for either the alert or the document.write. Save the changes (File->Save), then click the refresh button on your browser.
5. Q: Based on this experiment, which line of code is writing directly to the browser window, and which line of code is using the message box?
Write your answer here, below this line:
Add your name to the comments at the top of the file and save the program again as part1.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!
Note: that means I should see
<!-- your name here -->
at the top of the file. Example:
<!--Dikembe Wamutombo-->
<html>
Exercise 2: Using Variables For Input (4 points)
Rather than putting your name in the code, you will now add a variable so that you can enter your name once the program is running. To do this, you will need to create a variable (a storage location) to hold your name.
1. Make a copy of part1.html and save it as part2.html. You will be editing part2.html
2. Delete all the code between <script language="javaScript"> and </script>. Then, add the following lines in their place
[literally just copy and paste this code. Don’t change it]:
var name;
name = prompt ("Please enter your name","");
document.write("Hello " + name);
3. Save the updated file, then refresh your browser window. Run (refresh) the program several times, testing what happens if you click “OK” without first entering a name, and what happens if you click “Cancel” instead of “OK.”
4. Replace all the code between <script language="javaScript"> and </script> with the following, save the file, and run the program.
var x;
var y;
var answer;
x = prompt("Enter a number ");
y = prompt("Enter a number ");
document.write("You entered " + x + " and " + y);
document.write("<br>");
answer = prompt("Enter the sum of " + x + " and " + y);
document.write("You entered " + answer);
document.write("<br>");
After you run the program, clean up any spacing issues.
Debugging: If your program does not run, you will typically not see an error message displayed to the screen. If you are using Chrome, you may display error messages by following this procedure:
· Right click in white space in browser window
· Select Inspect element
· Select console
· The error may be displayed in red on the left. If it is not, click on the program file name (on the right). The error should be in the last line of code displayed.
If you still cannot see the error. Begin commenting out line by line (from bottom up) until you reach the line with the error.
5. Explain the purpose of the following line (if you’re not sure, remove the first occurrence of this line and see what happens).
document.write("<br>");
Write your theory of what the purpose is here, below this line. Make sure you have tested your hypothesis! Answer:
6. Now add these lines (below the last line of code) and save and run your program again. Test at least 3 different combinations of inputs, and record what numbers you added together, and what the result was.
var sum = x + y;
document.write("The sum is " + sum);
Test 1 :
x=
y=
sum=
Test 2 :
x=
y=
sum=
Test 3 :
x=
y=
sum=
7. Was that actually correct for your inputs?
Was it the correct answer:
8. How do you think the computer arrived at that answer?
Your explanation here:
9. Add these two lines of code just before the code you inserted for step #6, then save and run your program.
x = parseInt(x);
y = parseInt(y);
Is the program now displaying the actual correct answer? Why did this fix it?
Your explanation here:
Add your name to the comments at the top of the file and save the program again as part2.html. Include it in the zip file when you upload to Pilot.
Exercise 3: Using Conditionals (4 points)
1. In the program from Exercise 2, we have a variable storing the user’s answer and a variable storing the correct answer. We now want to add code so that a message is displayed indicating whether the user’s answer is right or wrong. To do this, delete the output line giving the correct answer, and then add the following code in its place:
if (answer == sum) {
document.write("That is correct!");
}
else {
document.write("That is not correct. The correct answer is " + sum);
}
2. Save and run your program several times to verify that it is working properly. Why is it important to run your program more than once to test if it works? Specifically, why must we run this program at least twice to test it properly?
Write your answer for why we have to test this program at least twice, here:
Add your name to the comments at the top of the file and save the program again as part3.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!
Exercise 4: Putting It All Together (12 points)
In this exercise, you are given a program description and must make a program to match it. You will be given example pictures as well.
PROGRAM DESCRIPTION:
The program should…
· Convert a temperature
· entered by the user
· from Celsius to Fahrenheit,
· OR from Fahrenheit to Celsius.
· The user will specify which conversion should be carried out.
So long as it asks the user for a temperature and which conversion to do, and converts the temperature correctly, the details are up to you. You may choose to follow the example pictures, or do your own thing.
1. Write out, in English, the sequence of steps the program should follow..
(4 points) Put your English description of the program here:
2. Using your English “program” as a guide, write a JavaScript program for the program described below.
(8 points) Save the program as part4.html, and include it in the zip file when you submit to Pilot, and back it up to your USB drive!
Mathematical Formulas:
The formula for converting to Celsius from Fahrenheit is:
Celsius temperature = (Fahrenheit temperature - 32) * 5/9;
The formula for converting to Fahrenheit from Celsius is:
Fahrenheit temperature = Celsius temperature * 9/5 + 32;
AFTER YOU HAVE WRITTEN THE PROGRAM, YOU SHOULD TEST IT:
Conversions that you should test:
· Enter 100, choose to convert from Celsius to Fahrenheit. Result: 212
· Enter 32, choose to convert from Celsius to Celsius. Result: 0
· Enter 212, choose to convert from Fahrenheit to Celsius. Result: 100
· Enter 75, choose to convert from Fahrenheit to Celsius. Result: 23.888888888889 (# of decimals may vary)
· Enter -40, choose either F or C. Result: -40 (-40 is the same in both scales)
Sample program runs (output) are shown on the following pages. You may choose to write your results in a message box rather than directly on the document.
EXAMPLES OF HOW THE PROGRAM SHOULD LOOK WHEN IT RUNS:
Example Program run 1:
Example Program run 2:
Part 4 (code may vary)
Add your name to the comments at the top of the file and save the program again as part4.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!
Exercise 5: Loops, Modifying Counter-Controlled Loops (16 points)
Part 5a (8 points)
Download the JSLoopsLab.html file from the Pilot Dropbox.
1. Every loop must have at least one loop variable, and each loop variable must have these three steps associated with it: an initialization step, a loop test, and an update step. In this case, the loop variable is counter. Identify the specific lines of code that perform each of the three steps on this variable (use the line numbers that appear to the left of the code).
Initialization step is accomplished? Answer here:
Loop test is accomplished? Answer here:
Update step is accomplished? Answer here:
2. What do you think would happen if the update step were not there? Check your answer by commenting out the update step and running the program. (Note: Again, to “comment out” a line of JavaScript code, just precede the line with double slashes //)
3. Modify the loop test so that it is run 10 times rather than 5. Write your new loop test here:
New loop goes here, below this line:
4. Change your initialization step so that counter = 1 to start with. Now, modify your loop test so that it is still run ten times. Write your new loop test here:
New loop test goes here, below this line:
5. A for loop can be used in place of a while loop. The syntax for the for loop is:
for (initialization step; loop test; update step)
{
//loop body
}
Modify this program so that it uses a for loop rather than a while loop. Run it to be sure you get the expected result.
Add your name to the comments at the top of the file, save as part5a.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!
Part 5b (8 points)
6. Write a loop that counts backward starting with the number 10 down to the number 1. Display each number to the screen.
Add your name to the comments at the top of the file, save as part5b.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!
Part OXC1. Rock Paper Scissors (Optional Extra Credit)
In this section, you will write a JavaScript program to simulate a modified (simple) version of Rock-Paper-Scissors game. Here’s how the simplified Rock-Paper-Scissors game work. In this version of the game, there will be two players playing Rock-Paper-Scissors game for one time (single round with both players throw shapes at each other only once). Each player will get a turn to throw a shape (Rock, Paper or Scissors). Winner of the game is decided based on the shape throw by each player using the following criteria.
a. If the first player throws a Rock and the second player throws a Scissor, the first player wins. In other words, Rock defeats Scissors.
b. If the first player throws a Scissor and the second player throws a Paper, the first player wins. In other words, Scissors defeats Paper.
c. If the first player throws a Paper and the second player throws a Rock, the first player wins. In other words, Paper defeats Rock.
d. If both players throw the same shape, the game is tied.
Now create a copy of the “hello world” file from Part 1, remove the two lines of JavaScript code there and rename the copied file to partOXC1.html. In this exercise, you will edit partOXC1.html.
1. First, write JavaScript code to create a welcome screen that greets users with the following message. “Welcome to Simplified Rock-Paper-Scissors Game”.
2. Now write code to read inputs from the two users. Since we cannot read shapes as inputs, use the following letters to represent each shape. So in your program, you will read any one of the following letters and treat them as shapes.
- Use ‘R’ to represent the shape Rock
- Use ‘P’ to represent the shape Paper
- Use ‘S’ to represent the shape Scissors
3. Now implement the game logic described above (from steps a to d) to decide the winner of the Rock-Paper-Scissors game based on the inputs you read from the two users. (Hint: Use nested if-else statements to implement game logic)
4. Please print the two inputs you read and the winner of the game into the Web page.
5. Check whether your program works correctly using the following inputs:
- User 1 enters ‘R’, User 2 enters ‘S’. Result: User 1 wins
- User 1 enters ‘S’, User 2 enters ‘P’. Result: User 1 wins
- User 1 enters ‘P’, User 2 enters ‘R’. Result: User 1 wins
- User 1 enters ‘S’, User 2 enters ‘S’. Result: Draw
- User 1 enters ‘R’, User 2 enters ‘P’. Result: User 2 wins
- User 1 enters ‘S’, User 2 enters ‘R’. Result: User 2 wins
- User 1 enters ‘P’, User 2 enters ‘S’. Result: User 2 wins
Sample program runs are shown in the images below. Your program should produce similar outputs to the figures shown below.
Add your name to the comments at the top of the file, save as partOXC1.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!
Part OXC2. Rock Paper Scissors Tournament (Optional Extra Credit)
In this section, you will extend the Simple Rock-Paper-Scissors game program you wrote in Part 4 - Section B. Create a copy of partOXC1.html file and rename the copied file to partOXC2.html. In this exercise, you will edit partOXC2.html.
1. Now, the two players who play Rock-Paper-Scissors game compete in a tournament. In this tournament, the two players play against each other five times. Whoever wins most number of games wins the tournament. If both players win same number of games, the tournament ends up in a tie.
2. Change the welcome message of your Rock-Paper-Scissors game to “Welcome to Simplified Rock-Paper-Scissors Tournament”. You should show this screen only once to the user.
3. Modify your Simple Rock-Paper-Scissors game to run five times using a loop. At the end of the each run, you will write to the screen who won that round. Once the users compete for five times, you will decide who wins the tournament based on the number of wins by each user. Your program should produce outputs similar to the figures shown below. (Screenshots for the changes you should do in Part 5 - Section C are displayed).
Add your name to the comments at the top of the file, save as partOXC2.html. Include it in the zip file when you upload to Pilot, and back it up to your USB drive!