Alam JAVA
Alam JAVA
Random;
import java.util.Scanner;
do {
System.out.print("Enter your guess (1-100): ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input! Please enter a number: ");
scanner.next();
}
guess = scanner.nextInt();
attempts++;
if (playAgain.equals("Y")) {
playGame();
} else {
System.out.println("Thank you for playing. Goodbye!");
}
scanner.close();
}
}
Title: Number Guessing Game Report
Introduction:
The "NumberGuessingGame" program is a simple Java game that allows
users to guess a randomly generated number between 1 and 100. The
objective of the game is to guess the correct number within the fewest
attempts possible. This report provides an overview of the code and its
functionality.
Code Overview:
The code begins by importing the necessary classes from the Java util
package, namely `Random` and `Scanner`. It then defines the main class,
`NumberGuessingGame`, which contains the main method responsible for
starting the game by calling the `playGame()` method.
The `playGame()` method is where the actual game logic resides. It initializes
a `Scanner` object to read user input and a `Random` object to generate a
random number between 1 and 100. It also declares and initializes variables
for tracking the number of attempts made by the player (`attempts`), the
user's guess (`guess`), and a flag indicating whether the user has won
(`hasWon`).
The game begins with a welcome message and an explanation of the rules. It
then enters a do-while loop, which continues until the user guesses the
correct number. Within the loop, the program prompts the user to enter their
guess and validates the input to ensure it is a valid integer between 1 and
100. If the input is invalid, the program prompts the user again until a valid
input is provided.
After the user guesses the correct number, the program asks if the user wants
to play again. If the user responds with "Y" (case insensitive), the
`playGame()` method is called recursively to start a new game. If the user
responds with any other input, a farewell message is displayed, and the
program terminates.
Lastly, the program closes the `Scanner` object to release system resources.
Conclusion:
The "NumberGuessingGame" program provides an interactive and
entertaining guessing game experience for the user. It demonstrates the use
of random number generation, user input validation, looping structures,
conditional statements, and recursion in Java. The code is well-structured and
easy to understand, making it an enjoyable game for players of all ages.