Concept Explanation
Time to combine everything from this module into one real program. The computer picks a secret number, the player guesses, and the program responds "too high" or "too low" until they get it.
This single project exercises variables, input, output, conditionals, loops, and boolean logic together — which is exactly how real code works.
What You Will Build
I picked a number between 1 and 100.
Guess: 50
Too high! Try again.
Guess: 25
Too low! Try again.
Guess: 37
Correct! You found it in 3 guesses.
The Full Program
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int secret = random.nextInt(100) + 1; // 1..100
int guess;
int attempts = 0;
boolean solved = false;
System.out.println("I picked a number between 1 and 100.");
while (!solved) {
System.out.print("Guess: ");
if (!sc.hasNextInt()) {
System.out.println("Numbers only, please.");
sc.next(); // discard the bad token
continue;
}
guess = sc.nextInt();
attempts++;
if (guess > secret) {
System.out.println("Too high! Try again.");
} else if (guess < secret) {
System.out.println("Too low! Try again.");
} else {
solved = true;
System.out.printf("Correct! You found it in %d guesses.%n", attempts);
}
}
sc.close();
}
}
How It Works, Piece by Piece
random.nextInt(100)returns 0–99, so+ 1shifts the range to 1–100.boolean solvedcontrols the loop. Setting it totrueis what ends the game.while (!solved)repeats until solved becomes true — the NOT operator reads as "while not solved".hasNextInt()guards against text input;sc.next()throws away the bad token so the loop can retry.attempts++increments the counter on every genuine guess.
Common Mistakes
- Off-by-one range:
random.nextInt(100)alone can return 0, which is outside your stated range. - Forgetting to discard bad input: Without
sc.next(), invalid text stays in the buffer and loops forever. - Comparing with
=:if (guess = secret)is assignment and will not compile. Use==.
Best Practices
- Name your constants:
final int MAX = 100;instead of repeating100. - Always guard user input: A crash on a typo is a poor experience.
- Give useful feedback: "Too high" teaches the player; "Wrong" does not.
Practice Exercises
- The Attempt Limit: Give the player only 7 guesses. If they run out, reveal the answer.
- The Rematch: After a win, ask "Play again? (yes/no)" and restart without relaunching the program.
- The Difficulty Menu: Let the player choose Easy (1–50), Medium (1–100), or Hard (1–500) before the game starts.