Lab: Java Object-Oriented Programming (OOP) - The Guessing Game
Here's an example of an object-oriented Java guessing game, where each algorithm is implemented in its own class:
import java.util.Random;
import java.util.Scanner;
// GuessingGame class represents the game itself
publicclassGuessingGame {
privatefinal int secretNumber;
private boolean isGameOver;
publicGuessingGame() {
Random random = newRandom();
secretNumber = random.nextInt(100) + 1; // Generate a random number between 1 and 100
isGameOver = false;
}
publicvoidplay() {
System.out.println("Welcome to the Guessing Game!");
while (!isGameOver) {
int guess = getGuessFromPlayer();
checkGuess(guess);
}
System.out.println("Congratulations! You guessed the number!");
}
private int getGuessFromPlayer() {
System.out.print("Enter your guess: ");
Scanner scanner = newScanner(System.in);
return scanner.nextInt();
}
privatevoidcheckGuess(int guess) {
if (guess == secretNumber) {
isGameOver = true;
} elseif (guess < secretNumber) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}
}
}
// Main class to start the game
publicclassMain {
publicstaticvoidmain(String[] args) {
GuessingGame game = newGuessingGame();
game.play();
}
}
In this example, the GuessingGame class represents the game itself.
It has a constructor that generates a random number between 1 and 100 as the secret number. The play() method starts the game and prompts the user for guesses until the correct number is guessed.
The getGuessFromPlayer() method is responsible for getting input from the player, and the checkGuess() method checks if the guess is correct, too low, or too high.
The game is started in the main() method of the Main class by creating an instance of GuessingGame and calling its play() method.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (