🎯 What you will learn
- Read input with Scanner
- Make random numbers with Random
- Combine loops and if statements in a game
👋 Let’s get started!
Let’s build a real game! 🎯 The computer picks a secret number from 1 to 100, and the player guesses until they get it — with “too high” and “too low” hints.
🪜 Step by step
1. 📥 Scanner reads input
Import Scanner, then use nextInt() to read a number.
import java.util.Scanner;
Scanner in = new Scanner(System.in);
int guess = in.nextInt();
2. 🎲 Random picks a number
nextInt(100) gives 0–99, so add 1 for 1–100.
import java.util.Random;
Random rand = new Random();
int secret = rand.nextInt(100) + 1;
3. 🔁 Loop until correct
Keep asking while the guess is wrong.
while (guess != secret) {
// ask again and give a hint
}
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
The full game (sample run)
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int secret = new Random().nextInt(100) + 1;
int guess = 0;
int tries = 0;
System.out.println("I picked a number from 1 to 100! 🎯");
while (guess != secret) {
System.out.print("Your guess: ");
guess = in.nextInt();
tries++;
if (guess < secret) {
System.out.println("Too low! ⬆️");
} else if (guess > secret) {
System.out.println("Too high! ⬇️");
}
}
System.out.println("You got it in " + tries + " tries! 🏆");
}
}The hint logic
if (guess < secret) {
System.out.println("Too low!");
} else if (guess > secret) {
System.out.println("Too high!");
} else {
System.out.println("Correct!");
}📖 Key words
Tap a card to flip it over!
- import
- Brings in tools from Java’s library 📦
- Scanner
- Reads what the user types 📥
- Random
- Makes random numbers 🎲
- !=
- Not equal ≠
🏆 Challenge
How to run it: ask a grown-up or teacher to install the free Java JDK, or use an online Java editor your school approves. Then remix it: add a limit of 7 tries and print “Out of tries!” if the player doesn’t win.
Challenge
int maxTries = 7;
while (guess != secret && tries < maxTries) {
// ...
}
if (guess != secret) {
System.out.println("Out of tries! It was " + secret);
}Knowledge Check Quiz
- What does rand.nextInt(10) + 1 give?
- Which class reads keyboard input?
- When does this loop stop?