๐ŸŽฏ Unit 2 Activities

Table of Contents


๐Ÿ’ป ACTIVITY PROGRAM SETUP INSTRUCTIONS
  1. Go to the public template repository for our class: BWL-CS Java Template
  2. Click the button above the list of files then select Create a new repository
  3. Specify the repository name: CS2-Unit2-Activity#

    Replace # with the specific activity number.

  4. Click

    Now you have your own personal copy of this starter code that you can always access under the Your repositories section of GitHub! ๐Ÿ“‚

  5. Now on your repository, click and select the Codespaces tab
  6. Click Create Codespace on main and 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:

  1. Navigate to the Source Control menu on the LEFT sidebar
  2. Click the button on the LEFT menu
  3. Type a brief commit message at the top of the file that opens, for example: updated main.py
  4. Click the small โœ”๏ธ checkmark in the TOP RIGHT corner
  5. Click the button on the LEFT menu
  6. 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-else blocks (chain structures) and conditions (boolean values or expressions).

PART A: Printing Randomly-Selected Messages

Write a branching program inside the main() method that does the following:

  1. Declare a variable called num and assign it a random integer between 1 to 10, inclusive.

    To review generating random numbers, see ๐Ÿ““ 1.11: Math Class

  2. Use conditional statements to test the value of num and 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 if block for every possibility after the first if statement, and before the final else block.

PART B: Coin Toss

  1. Generate another random number at the top of the program, this time arandom double between 0โ€“1. Store it in a variable called luck.
  2. In a nested if statement, check the value of luck. 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 if statements: use else if blocks to avoid multiple messages printing out.