Gurunanak Institutions Technical Campus
Ibrahimpatnam
Department of Computer Science(CS-Data Science)
Java Project: Number Guessing Game
This project involves creating a simple number guessing game in Java. In this game, the computer
selects a random number, and the user has to guess it within a limited number of attempts. It’s a fun,
interactive project suitable for beginners and offers practice with conditionals, loops, and user
input.
Project Objectives:
- Generate a random number between 1 and 100.
- Allow the user a limited number of attempts to guess the number.
- Provide feedback on each guess ('too high', 'too low', or 'correct').
- Display a win message if the guess is correct within the attempts.
- Reveal the correct answer if the attempts are exhausted.
Code Implementation:
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();
int maxAttempts = 5; // Maximum attempts allowed
int numberToGuess = random.nextInt(100) + 1; // Random number between 1 and 100
int attempts = 0;
boolean hasWon = false;
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("You have " + maxAttempts + " attempts to guess it.");
// Main game loop
while (attempts < maxAttempts) {
System.out.print("Enter your guess: ");
int userGuess = scanner.nextInt();
attempts++;
if (userGuess < numberToGuess) {
System.out.println("Too low! Try again.");
} else if (userGuess > numberToGuess) {
System.out.println("Too high! Try again.");
} else {
hasWon = true;
break;
}
System.out.println("Attempts remaining: " + (maxAttempts - attempts));
}
// Check if the player won or lost
if (hasWon) {
System.out.println("Congratulations! You've guessed the number in " + attempts + "
attempts.");
} else {
System.out.println("Sorry, you've used all attempts. The number was: " + numberToGuess);
}
scanner.close();
}
}
Explanation:
1. A `Random` object is used to generate a random number between 1 and 100.
2. The user is given a set number of attempts (5 by default) to guess the number.
3. After each guess, the program provides feedback on whether the guess was too high, too low, or
correct.
4. If the user guesses correctly, a congratulatory message is displayed.
5. If all attempts are used without a correct guess, the correct number is revealed.
Done By: Jayant Sharma
23WJ1A6731
CSD-1