Skip to content

Instantly share code, notes, and snippets.

@lakshyaraj2006
Created December 6, 2025 04:44
Show Gist options
  • Select an option

  • Save lakshyaraj2006/35697a7fac654c710042a4a25ad93247 to your computer and use it in GitHub Desktop.

Select an option

Save lakshyaraj2006/35697a7fac654c710042a4a25ad93247 to your computer and use it in GitHub Desktop.
Guess the number game. Java OOPs edition.
import java.util.Random;
import java.util.Scanner;
class Game {
int randNum;
int userNum;
int noOfGuesses = 0;
public Game() {
Random rand = new Random();
randNum = rand.nextInt(100);
}
public void takeUserInput() {
Scanner sc = new Scanner(System.in);
userNum = sc.nextInt();
}
public boolean isCorrectNumber() {
if (userNum > randNum) {
System.out.println("Your number is greater than the number!");
noOfGuesses += 1;
return false;
} else if (userNum < randNum) {
System.out.println("Your number is smaller than the number!");
noOfGuesses += 1;
return false;
} else {
System.out.println("You guessed the correct number!");
noOfGuesses += 1;
System.out.printf("Number of guesses: %d", noOfGuesses);
return true;
}
}
}
public class GuessTheNumber {
public static void main(String[] args) {
Game game = new Game();
do {
System.out.print("Enter your guess: ");
game.takeUserInput();
} while (!game.isCorrectNumber());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment