2.6

Random Numbers

AP Computer Science A

Math.random() review

java
double r = Math.random();  // e.g., 0.4826...
java
// Random int from 1 to 6 (dice roll)
int die = (int)(Math.random() * 6) + 1;

// Random int from 0 to 99
int percent = (int)(Math.random() * 100);

// Random int from 10 to 20
int num = (int)(Math.random() * 11) + 10;

The Random class

java
import java.util.Random;

Random rand = new Random();
int n = rand.nextInt(6);      // 0 to 5
int die = rand.nextInt(6) + 1; // 1 to 6
double d = rand.nextDouble();  // 0.0 to < 1.0
boolean b = rand.nextBoolean(); // true or false

Key Random methods

Random integers in a range (both approaches)

Working through examples

Coin flip simulator

java
import java.util.Random;

public class CoinFlip {
    public static void main(String[] args) {
        Random rand = new Random();
        int heads = 0;
        int tails = 0;
        
        for (int i = 0; i < 1000; i++) {
            if (rand.nextBoolean()) {
                heads++;
            } else {
                tails++;
            }
        }
        
        System.out.println("Heads: " + heads);  // ~500
        System.out.println("Tails: " + tails);   // ~500
    }
}

Dice game

java
public class DiceGame {
    public static void main(String[] args) {
        int die1 = (int)(Math.random() * 6) + 1;
        int die2 = (int)(Math.random() * 6) + 1;
        int total = die1 + die2;
        
        System.out.println("Roll: " + die1 + " + " + die2 + " = " + total);
        
        if (total == 7 || total == 11) {
            System.out.println("You win!");
        } else if (total == 2 || total == 3 || total == 12) {
            System.out.println("You lose!");
        } else {
            System.out.println("Point is: " + total);
        }
    }
}

Random password generator

java
public class PasswordGenerator {
    public static void main(String[] args) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        String password = "";
        
        for (int i = 0; i < 8; i++) {
            int index = (int)(Math.random() * chars.length());
            password += chars.charAt(index);
        }
        
        System.out.println("Password: " + password);
    }
}

Common AP exam patterns

Pattern 1: Random element from an array

java
String[] colors = {"red", "blue", "green", "yellow"};
int index = (int)(Math.random() * colors.length);
String pick = colors[index];

Pattern 2: Probability simulation

java
// 30% chance of rain
double chance = Math.random();
if (chance < 0.30) {
    System.out.println("Rain");
} else {
    System.out.println("No rain");
}

Pattern 3: Random within specific set

java
// Random even number from 2 to 20
int even = (int)(Math.random() * 10) * 2 + 2;
// Generates: 2, 4, 6, ..., 20

AP Exam Tips

Common Mistakes

Key Vocabulary