Learning to code is an essential skill for kids in today’s world, and machine language will be the new standard. Everything around us has some form of computer embedded within it; whether it’s your TV remote or microwave, they all operate using “machine codes”. Learning to code will help enhance your child’s logical thinking skills because he/she gets different challenges every time they solve an exercise or problem on their journey of learning any programming language. In this blog, we will see how a guessing game is developed in Java.

Skoolofcode strives toward helping students enjoy their journey while learning Java for beginners so that even those who might not initially show much interest can become hooked on programming.

Concepts to be learned by creating this game:

  • Loops
  • Conditional Statements
  • Methods

What is the Guessing Game?

A Guessing Game is a game where the computer will choose any random number between 1 and 100, and you have to guess that number. Every time you choose a number, the computer will tell you whether your guess is higher or lower than the number selected by the computer. Well, keep in mind that you only get six tries to guess the number. At the end of the game, it will tell you what number was chosen by the computer (if you are unable to guess the correct number). And, if you choose the correct number, then it tells you how many tries it took you to guess the number

Algorithm for the Guessing Game:

  1. A random number is picked by the computer.
  2. A user is asked to make a first guess.
  3. The user’s guess is matched with the random number picked by the computer.
  4. If the match is there, then you will get to see, “You got it right in ___ tries.”
  5. If the number is not matched, the computer tells you that the number the user wrote is higher or lower than the number chosen by it.
  6. Looking at the scenario again, the user will make a guess and write the number down.
  7. Steps 3-6 are repeated until 6 tries or the correct number is guessed (whatever comes first).
  8. If you guess the correct number before 6 tries, you will get to see, “You got it right in _____ tries.”
  9. If you didn’t get the number in 6 guesses, you will get “You did not get the number in 6 guesses. My number was _____. “
  10. .In the end, it will ask you if you would like to Play again and then display a thank you note.

Prerequisite

You will either need Java installed on your computer or you can write this program on repl.it (an online IDE).

Coding Time

It’s time to implement the algorithm and write the code.

We are going to let the computer choose any random number from 1–100.

Importing the Scanner class to take the input from the user:

import java.util.Scanner; 

public class GuessingGame {

The main Method starts here:

public static void main(String[] args) {
System. out.println("Let's play a game.  I'll pick a number between");
System.out.println("1 and 100, and you try to guess it.");

Scanner sc1 = new Scanner(System.in);  
boolean playAgain;
do {

Call subroutine to play one game:

playGame();              System.out.println("Would you like to play again?Y/N");
playAgain = sc1.nextBoolean();  
} while (playAgain);
System.out.println("Thanks for playing.  Goodbye.");
}           
        

PlayGame Method:

static void playGame() {

Random Numbers picked by the Computer

int computersNumber;            

Number entered by user as a guess:

int usersGuess;              

Number of guesses the user has made:

int guessCount;                 

The value assigned to computersNumber is a randomly (chosen integer between 1 and 100, inclusive):

computersNumber = (int)(100 * Math.random()) + 1;
                                         
guessCount = 0;
System.out.println();
System.out.println("What is your first guess? ");
Scanner sc= new Scanner(System.in);   
            while (true) {

Get the user’s guess:

usersGuess = sc.nextInt(); 
guessCount++;

The game is over; the user has won:

if (usersGuess == computersNumber) {
System.out.println("You got it in " + guessCount
                          + " guesses!  My number was " + computersNumber);
                  break; 
               }

The game is over; the user has lost:

if (guessCount == 6) {
System.out.println("You didn't get the number in 6 guesses.");
System.out.println("You lose.  My number was " + computersNumber);
                  break;  
              }

If we get to this point, the game continues.

Tell the user if the guess was too high or too low:

if (usersGuess < computersNumber)
 System.out.println("That's too low.  Try again: ");
else if (usersGuess > computersNumber)
   System.out.println("That's too high.  Try again: ");
            }
            System.out.println();
        }                    
     }

Source Code

Here is the final source code for the game:

import java.util.Scanner; 

public class GuessingGame {
     
        public static void main(String[] args) 
       {
           System.out.println("Let's play a game.  I'll pick a number between");
           System.out.println("1 and 100, and you try to guess it.");
           Scanner sc1 = new Scanner(System.in); 
           boolean playAgain;
           do {
              playGame();  // call subroutine to play one game
              System.out.println("Would you like to play again?Y/N");
              playAgain = sc1.nextBoolean();  
              } while (playAgain);
          System.out.println("Thanks for playing.Goodbye.");
        }         
        
        static void playGame() {
            int computersNumber; 
            int usersGuess;      
            int guessCount;      
            computersNumber = (int)(100 * Math.random()) + 1;
            guessCount = 0;
            System.out.println();
            System.out.println("What is your first guess?");
            Scanner sc= new Scanner(System.in);   
            while (true) {
               usersGuess = sc.nextInt();  
               guessCount++;
               if (usersGuess == computersNumber) {
                  System.out.println("You got it in " + guessCount
                          + " guesses!  My number was " + computersNumber);
                  break;  
               }
               if (guessCount == 6) {
                  System.out.println("You didn't get the number in 6 guesses.");
                  System.out.println("You lose.  My number was " + computersNumber);
                  break;  
               }
               if (usersGuess < computersNumber)
                  System.out.println("That's too low.  Try again:");
               else if (usersGuess > computersNumber)
                  System.out.println("That's too high.  Try again:");
            }
            System.out.println();
        } 
                    
     } 

 Are you seeking introductory or advanced online coding classes? At SkoolofCode, we offer project-based learning modules where students use live code to find logical and inventive solutions to problems. So, why wait and Book a FREE trial class today.

Happy Coding!!

By -Reena Verma