Generating Randomness: The Random Class
In many programs—like games, security tools, or simulations—you don't want the same result every time. You want the computer to "pick a number" In Java, we do this using the Random class.
1. Setting Up the Random Generator
Just like the Scanner, the Random tool lives in the java.util package. You must import it and create a "generator" object.
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Create the Random generator object
Random rnd = new Random();
// Generate a random integer
int myNum = rnd.nextInt();
}
}
2. Generating Numbers within a Range
By default, nextInt() can give you any number from -2 billion to +2 billion. Usually, we want a specific range (like 1 to 10).
To limit the range, we pass a number into the parentheses: nextInt(limit).
| Code | Range Result |
|---|---|
nextInt(10) |
Generates 0 to 9 |
nextInt(100) |
Generates 0 to 99 |
nextInt(6) + 1 |
Generates 1 to 6 (Like a real die) |
Pro Tip: The limit is exclusive. This means
nextInt(10)will never actually hit 10; it stops at 9. To include the number 10, usenextInt(11)ornextInt(10) + 1.
3. Other Random Types
You aren't limited to just whole numbers. You can generate random decimals or true/false values:
nextBoolean(): Returns eithertrueorfalse. Perfect for a coin flip!nextDouble(): Returns a decimal between0.0and1.0.
💻 Full Practical Example: The Number Guessing Game
Copy this code to see how Random, Scanner, and If-Else work together:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
// 1. Generate a target number between 1 and 10
int target = rand.nextInt(10) + 1;
System.out.println("--- The Secret Number Game ---");
System.out.print("Guess a number between 1 and 10: ");
int userGuess = input.nextInt();
// 2. Check the guess
if (userGuess == target) {
System.out.println("! You got it right. !");
} else {
System.out.println("Wrong! The number was: " + target);
}
input.close();
}
}
⚠️ Important Note on "Pseudo-Randomness"
Computer "randomness" isn't actually magic. Java uses a complex math formula based on the current time (the "Seed") to pick numbers. For games and basic apps, this is perfect. However, for high-level security or passwords, developers use SecureRandom.
💡 Challenge: The Digital Coin Flip
Write a program that:
- Generates a random boolean.
- If
true, prints "Heads". - If
false, prints "Tails". - Bonus: Ask the user for their choice first and tell them if they won!