Introduction
The Number Guessing Game is a classic beginner programming project that demonstrates core Java concepts such as random number generation, user input handling, loops, conditional logic, and basic game flow control. In this game, the computer generates a random number within a specified range (e.g., 1 to 100), and the player tries to guess it. After each guess, the program provides feedback—“too high” or “too low”—until the correct number is guessed. This guide provides a complete, well-structured implementation with input validation, attempt counting, and replay functionality.
Features of the Game
- Generates a random number between 1 and 100.
- Allows the player to make guesses via console input.
- Provides immediate feedback: “Too high”, “Too low”, or “Correct!”.
- Counts and displays the number of attempts taken.
- Validates user input (ensures only integers are accepted).
- Offers the option to play again after winning.
Complete Source Code
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
char playAgain;
System.out.println("=== Number Guessing Game ===");
System.out.println("I'm thinking of a number between 1 and 100.");
do {
int targetNumber = random.nextInt(100) + 1; // 1 to 100 inclusive
int attempts = 0;
int guess = -1;
while (guess != targetNumber) {
System.out.print("Enter your guess: ");
// Input validation
while (!scanner.hasNextInt()) {
System.out.println("Invalid input! Please enter a number.");
scanner.next(); // Discard invalid token
System.out.print("Enter your guess: ");
}
guess = scanner.nextInt();
attempts++;
if (guess < targetNumber) {
System.out.println("Too low! Try a higher number.");
} else if (guess > targetNumber) {
System.out.println("Too high! Try a lower number.");
} else {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
}
}
// Ask to play again
System.out.print("\nWould you like to play again? (y/n): ");
playAgain = scanner.next().toLowerCase().charAt(0);
} while (playAgain == 'y');
System.out.println("Thanks for playing! Goodbye.");
scanner.close();
}
}
How It Works
1. Random Number Generation
random.nextInt(100)returns a number from 0 to 99.- Adding
1shifts the range to 1–100.
2. Input Validation
- Uses
scanner.hasNextInt()to check if input is an integer. - If not, it discards the invalid input with
scanner.next()and reprompts. - Prevents
InputMismatchExceptionand ensures smooth gameplay.
3. Game Loop
- The inner
whileloop continues until the correct number is guessed. - Each valid guess increments the
attemptscounter. - Feedback is provided immediately after each guess.
4. Replay Functionality
- After a correct guess, the user is asked if they want to play again.
- The outer
do-whileloop restarts the game if the user enters'y'.
Sample Output
=== Number Guessing Game === I'm thinking of a number between 1 and 100. Enter your guess: 50 Too high! Try a lower number. Enter your guess: 25 Too low! Try a higher number. Enter your guess: 37 Too high! Try a lower number. Enter your guess: 31 Congratulations! You guessed the number in 4 attempts. Would you like to play again? (y/n): n Thanks for playing! Goodbye.
Key Concepts Demonstrated
| Concept | Implementation |
|---|---|
| Random Numbers | Random.nextInt() |
| User Input | Scanner class |
| Input Validation | hasNextInt() + loop |
| Loops | do-while (game replay), while (guessing) |
| Conditional Logic | if-else if-else for feedback |
| Variables & Counters | attempts, guess, targetNumber |
| String Handling | toLowerCase().charAt(0) for case-insensitive input |
Possible Enhancements
- Set difficulty levels (e.g., easy: 1–50, hard: 1–1000).
- Limit the number of attempts (e.g., max 7 guesses).
- Track high scores across sessions (save to file).
- Add a timer to measure how quickly the player guesses.
- Create a GUI version using JavaFX or Swing.
Best Practices Applied
- Input validation prevents crashes and improves user experience.
- Meaningful variable names (
targetNumber,attempts) enhance readability. - Resource management:
scanner.close()releases system resources. - Modular design: Clear separation of game logic and input handling.
- User-friendly prompts and feedback.
Conclusion
The Number Guessing Game is an excellent project for learning and practicing fundamental Java programming skills. It combines randomness, user interaction, and decision-making in a simple yet engaging format. The implementation provided here is robust, user-friendly, and extensible—making it ideal for beginners to study, run, and build upon. By completing this project, learners gain confidence in handling real-world programming tasks such as input validation, loop control, and game state management. Whether used as a learning exercise or a foundation for more complex games, this project reinforces core principles that are applicable across all areas of software development.