Share
Explore

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
public class GuessingGame {
private final int secretNumber;
private boolean isGameOver;

public GuessingGame() {
Random random = new Random();
secretNumber = random.nextInt(100) + 1; // Generate a random number between 1 and 100
isGameOver = false;
}

public void play() {
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 = new Scanner(System.in);
return scanner.nextInt();
}

private void checkGuess(int guess) {
if (guess == secretNumber) {
isGameOver = true;
} else if (guess < secretNumber) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}
}
}

// Main class to start the game
public class Main {
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
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 (
CtrlP
) instead.