๐ฏ Unit 2 Activities
Table of Contents
๐ป ACTIVITY PROGRAM SETUP INSTRUCTIONS
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository - Specify the repository name:
CS2-Unit2-Activity#Replace
#with the specific activity number. - Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositoriessection of GitHub! ๐ - Now on your repository, click and select the
Codespacestab - Click
Create Codespace on mainand wait for the environment to load, then youโre ready to code!
๐ When class ends, donโt forget to SAVE YOUR WORK! Codespaces are TEMPORARY editing environments, so you need to COMMIT changes properly in order to update the main repository for your program.
There are multiple steps to saving in GitHub Codespaces:
- Navigate to the
Source Controlmenu on the LEFT sidebar - Click the button on the LEFT menu
- Type a brief commit message at the top of the file that opens, for example:
updated main.py - Click the small
โ๏ธcheckmark in the TOP RIGHT corner - Click the button on the LEFT menu
- Finally you can close your Codespace!
๐ฎ ACTIVITY #1: Magic 8 Ball
Have you ever used a Magic 8 ball? You ask it a yes-no question, and then shake it to get a random answer like Signs point to yes!, Very doubtful, etc.
{:.highlight} Try out this Magic 8 Ball Simulator
In this activity, we will:
- Generate and use random values correctly.
- Practice selection with
if-else if-elseblocks (chain structures) and conditions (booleanvalues or expressions).
PART A: Printing Randomly-Selected Messages
Write a branching program inside the main() method that does the following:
- Declare a variable called
numand assign it a random integer between 1 to 10, inclusive.To review generating random numbers, see ๐ 1.11: Math Class
- Use conditional statements to test the value of
numand print out a different message for each number.Come up with 10 creative responses to yes-no questions!
Review: if-else if-else
if ( conditions ) {
statement1;
}
else if ( condition ) {
statement2;
}
else {
statement3;
}
This structure can accomodate more than 3 choices easily โ just add an
else ifblock for every possibility after the firstifstatement, and before the finalelseblock.
PART B: Coin Toss
- Generate another random number at the top of the program, this time arandom double between 0โ1. Store it in a variable called
luck. - In a nested
ifstatement, check the value ofluck. If it is greater than or equal to 0.5, print the message"LUCKY! ๐"
Common pitfalls to avoid
- Off-by-one:
(int) (Math.random() * 10)gives values between 0โ9. Remember to add 1. - Isolated
ifstatements: useelse ifblocks to avoid multiple messages printing out.