Created
December 6, 2025 04:44
-
-
Save lakshyaraj2006/35697a7fac654c710042a4a25ad93247 to your computer and use it in GitHub Desktop.
Guess the number game. Java OOPs edition.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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