How To Create A Guessing Game in Java For Beginners


Hey, Welcome to the Practicehouse. Today in this java tutorial we will learn about java OOP concept and we will create a Guessing Game in Java.

Summary: This Guessing Game involves a Game Object and Three Player Object. Now the Game Object will generate a random number between 0 and 9. Three player objects will try to guess that number. ( Not exciting at all ).

We will have 3 classes:,,

The logic behind this: very simple logic behind this :

  1. First, the Main class has the main method so it will start our game . in this class we ill create an instance of our GuessGameJava class where all things will happen. it has a startGame() we will call this method from our main class.
  2. Inside the startGame() Method we will create 3 Players object. we will generate a random number and we will ask our players also to guess the number. We will check if it’s matched then we will print our winner information either they will try again.

Very simple isn’t it. Let’s have a look at code.

Main Class of Guessing Game in Java.

As you see in our Main Class we have created an instance of GuessGameJava Class And then we call startGame() method from our GuessGameJava class.

So let’s have a look at GuessGameJava class of Guessing Game in Java

As you can see that we have our GuessGameJava class and inside we have a method call startGame().

Inside this method, all the things are happening. we created our players object and we generate the random number. we ask our players to guess the number and then we check the number and finally if it’s matched then we print our winner information either we give them the chance to try again.

So here is our Player class of Guessing Game in Java.

That’s all we needed. Now let’s run our program and see how it is looks when it performs.

Output Sample of Guessing game in Java:

As you can see our players have to guess the Number 7. First, try nobody guesses 7 but in the second time, Player 2 is guessed 7. Hurray, we have found our winner.

let’s see another sample output.

This time it runs quite a few times already to find our winner. Finally, Player 1 is our winner.

Clone / Download the Sample Project from GitHub : Download / Clone Sample Project

So this program is for newbies in java programming. I hope you enjoyed and learn something. I wish you all the best.

Thank you so much for visiting my blog. If you want more content like this please inspire me by writing a comment below.

Leave a Reply

Notify of