# Java - Guess Number in 5 attempts

Guessing a Number (0 - 100) would be interesting program. Here you can find the complete source code in Java Programming Language.

The program will generate a random number between 0 - 100 and keep it as a secret number. Your job is find out the secret number in 5 attempts. Each time you guess you will get the message like given below:

1. Very High or Very Low (> 50)

2. High or Low (<50 and > 30)

3. Moderately High or Moderately Low (<30 and > 15)

4. Somewhat High or Somewhat Low (< 15)

In case, the secret number is 86, if you enter your choice as 10, then you will get the message "Very Low". It means you have to increase your choice by at least 50. Let's say the second choice you give out is 60, then the message "Moderately Low". Then you can assume the secret number is in between (75 - 90). Then your 3rd choice would be 83 and the message "Somewhat Low". Now you know the secret number is in between 84 - 90. Then your 4th choice is: 86. Now you won and found out the correct number in 4 attempts.

## Source Code

import java.io.*;

import java.lang.*;

import java.util.*;

class GuessNumber

{

{

try

{

String inpString = "";

return Integer.parseInt(s);

}

catch (Exception e)

{

e.printStackTrace();

}

return -1;

}

public static void main(String[] args)

{

int x = (int)(Math.random() * 100);

System.out.println("Welcome to Guess a Word Program (0-100) with in 5 attempts.\n");

boolean bGuessedCorrectly = false;

for (int i = 1; i <= 5; i++)

{

System.out.print("ATTEMPT " + i + ": Enter the your number: ");

if (n == x)

{

System.out.println("Congrats! You have guessed the number correctly");

bGuessedCorrectly = true;

break;

}

int diff = (int)(Math.abs(x - n));

boolean bMoveHigher = false;

if(x > n)

bMoveHigher = true;

if(diff >= 50)

{

if (bMoveHigher == false)

else

}

else if (diff >= 30)

{

if (bMoveHigher == false)

else

}

else if (diff >= 15)

{

if (bMoveHigher == false)

else

}

else

{

if (bMoveHigher == false)

else

}

}

if (bGuessedCorrectly == false)

{

System.out.println("Unfortunately you did not guess it correctly. The correct number is: " + x);

}

}

}

## Output

Welcome to Guess a Word Program (0-100) with in 5 attempts.

ATTEMPT 1: Enter the your number: 50

ATTEMPT 2: Enter the your number: 28

ATTEMPT 3: Enter the your number: 24