Guess The Number Game in Java — 2

Minhajul Alam
2 min readDec 13, 2018

--

In my previous article, we build Guess The Number Game in Java — 1. Now we will add two more features in this game. These are —

  1. User can set turn, upper and lower limit.
  2. If user can’t guess the number, we will tell them the random number with a message.

Build Process:

For adding these features, we have to take input from the user. At the beginning, we will take turn limit, upper and lower limit input from user.

Now for checking the turn limit is over or not we have to take a variable before the while loop and named this variable counter and we will set this equal to 1. In while loop, we will set condition (counter≤turnLimit). At the end of the while loop we will increment counter variable by one.

If user can’t guess the number we will tell them the random number that our program generated. We can do this in many ways. But here we will do this using a Boolean type variable named flag. If user guess the right number we will set flag = true, else flag = false. After the while loop we will check (flag == false). If this condition is true then we will show them the random number with a message.

Implementation

Full Code:

import java.util.Random;
import java.util.Scanner;

public class GuessTheNumber {
public static void main(String args[]){

//creating scanner
Scanner scanner = new Scanner(System.in);

System.out.println("Enter turn limit");
int turnLimit = scanner.nextInt();

System.out.println("Enter lower limit");
int lowerLimit = scanner.nextInt();

System.out.println("Enter upper limit");
int upperLimit = scanner.nextInt();

//creating instance of Random() class
Random rand = new Random();

//creating a int type variable
int randomInteger;

//storing random number in randomInteger variable
randomInteger = lowerLimit + rand.nextInt(upperLimit);

int counter = 1;
boolean flag = false;
while(counter<=turnLimit){

System.out.print("User Input:");
//storing user input in userInput variable
int userInput = scanner.nextInt();

//checking conditions and showing messages
if(userInput==randomInteger){
System.out.println("Congratulation");
flag = true;
break;
}else if(userInput>randomInteger){
System.out.println("Guess Lower");
flag = false;
}else{
System.out.println("Guess Higher");
flag = false;
}

//incrementing counter variable
counter++; //counter = counter + 1;
}
if(flag == false){
System.out.println("GAME OVER");
System.out.println("Computer Generated Random Number is : "+randomInteger);
}
}
}

Output:

Enter turn limit
3
Enter lower limit
1
Enter upper limit
10
User Input:1
Guess Higher
User Input:2
Guess Higher
User Input:6
Guess Lower
GAME OVER
Computer Generated Random Number is : 4

Congratulation!

You made Guess The Number Game.

Now we will make this game in Android. Let’s go…

--

--