This article is going to be interested because we are going to teach you how to write a Java Program To Guess A Number Game. We recently published a Java program to check an identity matrix. So, let’s start creating this game without wasting the time.
Java Program To Guess A Number Game:
In this section, we will discuss the logic of the program. First, we have to understand what the code will do. We have used a Random library which generates the random number within the range and the second library is used to take the value of our number from the user because we have to guess the number that the compiler generated randomly.
The random number generated by the compiler is stored in some variable and the ‘number’ variable is used to take the guessing number from the user. Next, we used a do-while loop and simply use an else-if ladder. If the number is greater it will show the number is greater and increment in the guesses variable and again take the value from the user if the number is smaller second condition and the respective block will execute showing the message the number is smaller and increment in the guesses and again take the value.
While (true) means the loop will run until you will not guess the number. The loop will iterate until the generated number from the compiler is not equal to your number. When your number is equal to the generated number it will show the output that your number is now equal and also increase the value of the guess with 1 and the break statement is used to jump from the loop. And in the main function, it will print the random number generated by the compiler and show you how many attempts you guess the number.
Source Code Of Java Program To Guess A Number Game:
import java.util.*; import java.util.Random; public class GuessGame { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int randomNumber = (int)(100.0 * Math.random()); int guesses = 0; int number; do { System.out.println("Enter Your Number : "); number = sc.nextInt(); if(number>randomNumber){ System.out.println("Your Number Is Greater"); guesses++; } else if(number<randomNumber){ System.out.println("Your Number Is Smaller "); guesses++; } else{ System.out.println("Your Number Is Now Equal "); guesses++; break; } }while(true); System.out.println("Random Number Generated is : "+randomNumber); System.out.println("You Guess "+randomNumber+" In "+guesses+" Guesses"); } }
Output:
Conclusion:
From the above program, we conclude how to write a Java Program to Guess A Number Game. We hope that you understand the logic of the program very clearly. If you have any problem related to this program or any other program kindly comment. We will help you.