๐ŸŽฏ 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-Unit-2-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!

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.

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 ( condition ) {
  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 make it a random double between 0โ€“1. Store it in a variable called luck.
  2. In a nested if statement (inside one of your existing conditional blocks) test the value of luck as a โ€œfollow upโ€ after printing the Magic 8 Ball message.
  3. If it is greater than or equal to 0.5, print the message "LUCKY! ๐Ÿ€"

Review: nested if

if ( condition ) {
  statement1;
  if ( condition ) {
    statement2;
  }
}