π― Unit 1 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-Unit1-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 repositories
section of GitHub! π - Now on your repository, click and select the
Codespaces
tab - 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:
- Navigate to the
Source Control
menu 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: MadLibs
In this activity, youβll be creating your own MadLibs game using Java! A MadLibs story is a short story where certain words are left out, and players fill in the blanks with their own words (like nouns, verbs, adjectives, etc.), making the story fun and creative. You will write a story, replace some words with variables, and ask the user to fill in those blanks by gathering input using a Scanner
object.
Reminders
- Strings in Java are objects of the
String
class that hold sequences of characters. - String objects can be created by using string literals (
String s = βhiβ;
) or by calling the String class constructor (String t = new String(βbyeβ);
). - String objects can be concatenated using the
+
or+=
operator, resulting in a new String object. - Primitive values can be concatenated with a String object. This causes implicit conversion of the values to String objects.
PART A: Create a MadLibs Story
-
Come up with a fun story to use for MadLibs. Yours should be long enough to include at least 10 variables. Choose nouns, verbs, adjectives, etc., that you want the user to fill in, and decide how many blanks youβll need. Write the full story in a
// comment
with placeholders like below.Example: βToday, I went to the PLACE to VERB with my ADJECTIVE NOUN. It was a ADJECTIVE day, and we had lots of fun!β
-
In your
main
method, declare variables for the parts of the story that will be filled in. For now, manually assign values to each variable in your code.Example:
String adjective1 = "funny"; String place1 = "park"; String verb1 = "dance";
-
Use string concatenation to combine your variables with the rest of the story.
Example:
String sentence1 = "Today, I went to the " + place1 + " to " + verb1 + " with my " + adjective1 + " friend!";
-
Print out your story!
It will be easier to separate each sentence into its own variable and/or print statement, rather than build one giant string for the whole story.
PART B: Interactive Story with Scanner
Input
-
At the top of your program, import the Scanner class:
import java.util.Scanner;
-
In your
main
method, construct the Scanner (only once):Scanner scan = new Scanner(System.in);
-
For each variable in your story, prompt the user for input and store it:
System.out.print("Enter an adjective: "); String adjective1 = scan.nextLine();
-
Use string concatenation to build your story as before, but this time the variables contain the userβs input.
-
Print the completed story to the console.
-
Test it out by running your program multiple timesβeach time, enter different values to create unique stories!
Optional Challenges
- Add more variables to make your story longer and funnier.
- Format the output to make it look like a paragraph using
\n
for new lines. - Include emojis to make the story visually interesting!
- Take numerical input (
int
anddouble
) by using theScanner
class methods:scan.nextInt()
orscan.nextDouble()
, for at least 2 of the variables in your story. - ADVANCED: Before including those numbers in your story, run a
Math
class method on them to manipulate the numbers however youβd like. You should use at least 2 Math class methods total here, and possiblyMath.random()
to include a random number somewhere in the story.Refer to π 1.11: Math Class
- ADVANCED: Manipulate some of the string variables with
String
class methods such as.substring()
. Use at least 3 String class methods total.Refer to π 1.15: String Class
ποΈ ACTIVITY #2: Construction Calculator
You just got a summer job shadowing a contractor on a construction site. Your boss isnβt too impressed with your manual labor skills, city kid, but maybe you can shine on the engineering side of it. If you can make your initial calculations quickly, that gives you more time to struggle with the building part!
In this activity, youβll write some Java methods to help you with various tasks on the job.
PART A: Unit Conversions
Contractors constantly need to convert between units: feet to inches, yards to feet, and meters to centimeters. Your boss says if you canβt do this in your head, at least make the computer do it for you!
- Copy the starter code for the method below into your program (outside of the
main
method, but still inside theMain
class):public static double feetToInches(double feet) { double inches; // TODO: Convert feet to inches (1 foot = 12 inches) return inches; }
- Complete the method body by multiplying the number of
feet
by12
to getinches
. - Call your method from the
main()
method withfeet = 8
.- Store the result in a variable, e.g.
double result = feetToInches(8);
- Store the result in a variable, e.g.
- Print the result using string concatenation:
EXPECTED OUTPUT:
8.0 feet = 96.0 inches
- Optional Challenge:
- Add more conversion methods on your own.
yardsToFeet
(1 yard = 3 feet)metersToCentimeters
(1 meter = 100 centimeters)
- Add more conversion methods on your own.
PART B: Ladder on Tower
One common use for the Pythagorean theorem is to calculate the length of ladder you will need to reach your work bestie, who got stuck standing at the top of a tower surrounded by a moat. The ladder will be the hypotenuse of a triangle whose legs are the height of the tower and the width of the moat (since you have to place the base of the ladder on the edge of the moat).
The Pythagorean theorem is named for Pythagoras, who was also the leader of the gang of Greek mathematicians who legend has it allegedly drowned their fellow mathematician for showing that
β2
is irrational.
- Copy the starter code for the method below into your program (outside of the main method, but still inside the
Main
class):public static double calcLadderSize(double height, double width) { double ladderSize; // TODO: Calculate using Pythagorean theorem // Use Math.sqrt and Math.pow or * return ladderSize; }
- Complete the
calcLadderSize
method body usingMath.sqrt()
andMath.pow()
in the Pythagorean theoremc = β(aΒ² + bΒ²)
a
= height of the towerb
= width of the moatc
= ladder length
- Call your method from the
main()
method withheight
= 30 andwidth
= 40. Make sure to store the result in a variable.HINT:
double size = ...
- Use string concatenation to print out a sentence with the calculated
size
:EXPECTED OUTPUT:
Bestie, I need a 50.0 foot ladder!
PART C: Random Supply Delivery
On a real construction site, supplies donβt always arrive in the exact amounts you expect. To simulate this chaos, youβll use the Math.random()
method to generate random numbers for a delivery of wood planks.
Recall:
Math.random()
returns a decimal between 0.0 (inclusive) and 1.0 (exclusive). You can multiply it to scale the range, and cast toint
if you want whole numbers.
- Write a method called
randomPlankDelivery
that generates a random number of planks between 10 and 50 (inclusive).public static int randomPlankDelivery() { int planks; // TODO: Use Math.random to generate an int from 10 to 50 return planks; }
- Inside the method, use the formula:
planks = (int)(Math.random() * 41) + 10;
Math.random() * 41
β gives a number between 0.0 and 40.999β¦- Adding
10
shifts it into the range 10β50. - Casting to
(int)
gives a whole number.
- In your
main()
method, call the method 3 times to simulate 3 separate deliveries.int delivery1 = randomPlankDelivery(); int delivery2 = randomPlankDelivery(); int delivery3 = randomPlankDelivery();
- Print the results in a clear sentence for each delivery, for example:
First truck delivered 32 planks. Second truck delivered 48 planks. Third truck delivered 15 planks.
- Optional Challenge:
- Add all three deliveries together and print the total number of planks delivered.
EXPECTED OUTPUT:
Total planks delivered: 95
- Add all three deliveries together and print the total number of planks delivered.