In this article, we will implement Number guessing game in java.
Table of Contents
guesses
a number between a range
. If player guesses the exact number then player wins else player looses the game. Since this game provides limited attempts, so, player must guess the number with the limited attempts, else will lose the game.
Let’s understand the game and its rules.
Number guessing game Rules
- You must enter only valid integer within the specified range.
- You will be provided limited attempts to guess the number.
- You cannot leave the game, once started.
If the entered number is less than or greater than the required number, then player gets the message (hint) to proceed further either in up or down range.
Algorithm for Number guessing game
Step 1:
Create three variables attempt
, userGuessNumber
, secretNumber
and initialize them.
Step 2:
Generate a random number and assigned to secretNumber
.
Step 3:
Start a loop and take user input.
Step 4:
Validate user input and match with the secretNumber.
Step 5:
If userGuessNumber
is greater than or less than the secretNumber
then print a message to user.
Step 6:
If userGuessNumber
is equal to the secretNumber
, then user wins and exit the game.
Step 7:
If number of attempts exceeds the limit
, exit the game.
Step 8:
Repeat from Step 3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package org.arpit.java2blog; import java.util.Scanner; public class Main { public static void main(String args[]) { int attempt = 1; int userGuessNumber = 0; int secretNumber = (int) (Math.random() * 99 + 1); Scanner userInput = new Scanner(System.in); System.out.println("Welcome to Guess Number Game \nYou Will Be Asked To Guess A Number To Win The Game \nYou have Maximum 5 Attemp Limit"); do { System.out.print("Enter a guess number between 1 to 100\n"); if(userInput.hasNextInt()) { userGuessNumber = userInput.nextInt(); if (userGuessNumber == secretNumber) { System.out.println("OOhhOO!, Your Number is Correct. You Win the Game!"); break; } else if (userGuessNumber < secretNumber) System.out.println("Your Guess Number is Smaller."); else if (userGuessNumber > secretNumber) System.out.println("Your Guess Number is Greater."); if(attempt == 5) { System.out.println("You have exceeded the maximum attempt. Try Again"); break; } attempt++; }else { System.out.println("Enter a Valid Integer Number"); break; } } while (userGuessNumber != secretNumber); } } |
Output
You Will Be Asked To Guess A Number To Win The Game
You have Maximum 5 Attemp Limit
Enter a guess number between 1 to 100
75
Your Guess Number is Greater.
Enter a guess number between 1 to 100
45
Your Guess Number is Smaller.
Enter a guess number between 1 to 100
58
Your Guess Number is Smaller.
Enter a guess number between 1 to 100
67
Your Guess Number is Greater.
Enter a guess number between 1 to 100
62
OOhhOO!, Your Number is Correct. You Win the Game!
That’s all about Number guessing game in java.