The Problem: Building a Game Without Math Class

Imagine you’re creating a simple RPG game and you need to:

  • Calculate a player’s damage: 10 × (1.5level)
  • Find the distance between the player and an enemy
  • Generate random loot drops
  • Round numbers for displaying stats

Without the Math class, you’d have to write your own code for all of this! That would be hundreds of lines of complicated algorithms.

With the Math class? Just a few simple method calls!

Think About This:

  • Have you ever used the x² or √ button on a calculator?
  • When might you need to generate a random number in a program?
  • Why would we want to round 47.8 to 48?

Let’s learn how Java’s Math class makes all of this easy!

What is the Math Class?

The Math Class is a special tool built into Java that lets you do complex math operations easily.

College Board Essential Knowledge (1.11.A.1):

  • The Math class is part of the java.lang package
  • You don’t need to import it - it’s automatically available in every Java program
  • It contains only static methods (you call them using Math.methodName())

Think of it like having a scientific calculator built right into your code!

Learning Objective (College Board 1.11.A)

By the end of this lesson, you will be able to:

Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced

In simple terms: You’ll learn to use Math class methods in your code and understand what they return!

What you’ll master:

  1. Using Math.abs() to get absolute values
  2. Using Math.pow() to calculate powers
  3. Using Math.sqrt() to find square roots
  4. Using Math.random() to generate random numbers
  5. Manipulating random values to create specific ranges

Important Math Class Methods (College Board 1.11.A.2)

These are the methods you NEED to know for the AP CSA exam:

Method What It Does Example
Math.abs(int x) Returns the absolute value of an integer Math.abs(-5) returns 5
Math.abs(double x) Returns the absolute value of a double Math.abs(-7.5) returns 7.5
Math.pow(double base, double exponent) Returns base raised to the power of exponent Math.pow(2, 3) returns 8.0
Math.sqrt(double x) Returns the square root of x Math.sqrt(25) returns 5.0
Math.random() Returns a random number from 0.0 (inclusive) to 1.0 (exclusive) Math.random() might return 0.537

Key Points to Remember:

  1. All these methods are static - call them with Math.methodName()
  2. Most return double values
  3. Math.random() always returns a value where 0.0 ≤ value < 1.0
  4. You can manipulate Math.random() to get different ranges (we’ll learn this!)

Let’s See Them in Action!

Now let’s write code using each of these methods. Follow along and run the code yourself!

Example 1: Math.abs() - Absolute Value

// Math.abs() removes the negative sign from a number

int playerHealth = 75;
int enemyHealth = 120;
int difference = playerHealth - enemyHealth;  // This is -45

System.out.println("Raw difference: " + difference);
System.out.println("Absolute difference: " + Math.abs(difference));

// Use case: Find out WHO has more health, not if it's positive or negative
System.out.println("\nThe health gap is " + Math.abs(difference) + " HP");

Example 2: Math.pow() - Powers/Exponents

// Math.pow(base, exponent) calculates base^exponent

// Example: Calculate damage that increases with level
double baseDamage = 10.0;
int level = 5;

// Damage formula: baseDamage * (1.5^level)
double totalDamage = baseDamage * Math.pow(1.5, level);

System.out.println("Base Damage: " + baseDamage);
System.out.println("At level " + level + ", damage is: " + totalDamage);

// Another example: 2^10
System.out.println("\n2 to the power of 10 = " + Math.pow(2, 10));

Example 3: Math.sqrt() - Square Root

// Math.sqrt() finds the square root

// Use case: Distance formula (Pythagorean theorem)
// Distance = √((x2-x1)² + (y2-y1)²)

double playerX = 3.0;
double playerY = 4.0;
double enemyX = 0.0;
double enemyY = 0.0;

// Calculate distance
double distance = Math.sqrt(Math.pow(playerX - enemyX, 2) + Math.pow(playerY - enemyY, 2));

System.out.println("Player is at (" + playerX + ", " + playerY + ")");
System.out.println("Enemy is at (" + enemyX + ", " + enemyY + ")");
System.out.println("Distance between them: " + distance + " units");

Example 4: Math.random() - Random Numbers

// Math.random() returns a value: 0.0 <= value < 1.0
// This means it can be 0.0, but will NEVER be exactly 1.0

System.out.println("Basic random number: " + Math.random());
System.out.println("Another one: " + Math.random());
System.out.println("And another: " + Math.random());

// These will all be different numbers between 0.0 and 1.0
// Examples: 0.374, 0.891, 0.025, etc.

The MOST Important Part: Manipulating Math.random()

College Board Essential Knowledge (1.11.A.3):

The values returned from Math.random() can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range

This is crucial for the AP exam! Let’s learn how to create random numbers in ANY range you want.

Step-by-Step: Creating Random Integers in a Range

Goal: Get a random integer from min to max (inclusive)

Formula:

(int)(Math.random() * (max - min + 1)) + min

Let’s break this down!

// Example: Random number from 1 to 6 (like a dice roll)

int min = 1;
int max = 6;

// Step 1: Math.random() gives us 0.0 to 0.999...
// Step 2: Multiply by (max - min + 1) = 6, gives us 0.0 to 5.999...
// Step 3: Cast to int, gives us 0 to 5
// Step 4: Add min, gives us 1 to 6

int diceRoll = (int)(Math.random() * (max - min + 1)) + min;

System.out.println("You rolled a: " + diceRoll);

// Try it a few more times!
System.out.println("Roll 2: " + (int)(Math.random() * 6) + 1);
System.out.println("Roll 3: " + (int)(Math.random() * 6) + 1);
System.out.println("Roll 4: " + (int)(Math.random() * 6) + 1);

// Another example: Random damage from 50 to 100

int minDamage = 50;
int maxDamage = 100;

int damage = (int)(Math.random() * (maxDamage - minDamage + 1)) + minDamage;

System.out.println("Damage dealt: " + damage);

// Generate 5 random damage values
System.out.println("\n5 Attacks:");
for (int i = 1; i <= 5; i++) {
    int randomDamage = (int)(Math.random() * 51) + 50;  // 51 because (100-50+1)=51
    System.out.println("Attack " + i + ": " + randomDamage + " damage");
}

Popcorn Hack #1: Power Level Calculator

Your Task: Create a program that calculates a character’s power level.

Requirements:

  • Base power = 100
  • Power formula: basePower * (1.2)^level
  • Ask user for their level (or hard-code level = 10)
  • Use Math.pow() to calculate final power
  • Print the result

Example Output:

Level: 10
Base Power: 100
Final Power: 619.17 (approximately)
// YOUR CODE HERE for Popcorn Hack #1

double basePower = 100;
int level = 10; // you can change or input this later if needed
double finalPower = basePower * Math.pow(1.2, level);

System.out.println("Level: " + level);
System.out.println("Base Power: " + basePower);
System.out.printf("Final Power: %.2f (approximately)%n", finalPower);
Level: 10
Base Power: 100.0
Final Power: 619.17 (approximately)





java.io.PrintStream@77e81102

Popcorn Hack #2: Loot Drop Simulator

Your Task: Create a simple loot drop system that generates random items.

Requirements:

  • Generate a random item rarity (1-100)
    • 1-60: Common (worth 10-30 gold)
    • 61-85: Rare (worth 31-70 gold)
    • 86-100: Legendary (worth 71-100 gold)
  • Use Math.random() to generate the rarity number
  • Use Math.random() again to generate gold value within the range
  • Print what you got!

Example Output:

Loot Drop!
Rarity Roll: 73
You got: RARE item
Gold Value: 54

Hint: You’ll need to use if-else statements with your random numbers!

// YOUR CODE HERE for Popcorn Hack #2

System.out.println("Loot Drop!");

// Generate a random rarity roll between 1 and 100
int rarityRoll = (int)(Math.random() * 100) + 1;
System.out.println("Rarity Roll: " + rarityRoll);

String rarity;
int goldValue;

// Determine rarity and gold range
if (rarityRoll <= 60) {
    rarity = "COMMON";
    goldValue = (int)(Math.random() * (30 - 10 + 1)) + 10; // 10–30
} else if (rarityRoll <= 85) {
    rarity = "RARE";
    goldValue = (int)(Math.random() * (70 - 31 + 1)) + 31; // 31–70
} else {
    rarity = "LEGENDARY";
    goldValue = (int)(Math.random() * (100 - 71 + 1)) + 71; // 71–100
}

// Print results
System.out.println("You got: " + rarity + " item");
System.out.println("Gold Value: " + goldValue);

Quick Summary - What You Learned

Key Methods to Remember:

  1. Math.abs(x) - Makes any number positive
  2. Math.pow(base, exp) - Calculates powers (like 2³)
  3. Math.sqrt(x) - Finds square roots
  4. Math.random() - Generates random numbers (0.0 to 1.0)

The Important Formula:

Random integer from min to max (inclusive):

(int)(Math.random() * (max - min + 1)) + min

College Board Key Points:

Math class is in java.lang (automatically available)
All methods are static
Math.random() returns: 0.0 ≤ value < 1.0
You can manipulate random() to get any range you want


Homework Checklist

What to Submit:

  1. Popcorn Hack #1: Power Level Calculator
  2. Popcorn Hack #2: Loot Drop Simulator

Before You Submit:

  • Both popcorn hacks are complete and run without errors
  • Your code has comments explaining what it does
  • You’ve tested your code with different values
  • You completed the homework assignment

Questions? Ask in class or on Slack!

Pro Tip: The random number formula is VERY commonly tested on the AP exam. Make sure you understand it!