# Guess The Number Game Using Java with Source Code

Today we will know how to make this game in Java.

Here is the source code for our “.java” file

import java.util.Random; import java.util.Scanner; public class codespeedy { public static void main(String[] args) { Random Random_number= new Random(); int right_guess=Random_number.nextInt(100); int turns=0; Scanner scan=new Scanner(System.in); System.out.println("Guess a number between 1 to 100, You will have 10 turns!" ); System.out.println("best of luck!"); int guess; int i=0; boolean win=false; while(win==false) { guess=scan.nextInt(); turns++; if(guess==right_guess) { win=true; } else if(i>8){ System.out.println("You loose! the right answer was: "+right_guess); return; } else if(guess<right_guess){ i++; System.out.println("Yor Guess is lower than the right guess! Turns left: "+(10-i)); } else if(guess>right_guess) { i++; System.out.println("Your Guess Is Higher Than THe Right Guess! Turns left: "+(10-i)); } } System.out.println("YOu win!"); System.out.println("Then number was "+right_guess); System.out.println("You used "+turns+" turns to guess the right number"); System.out.println("Your score is "+((11-turns)*10)+" out of 100"); } }

**Algorithm:**

- First, you have to take a random number and store it to an integer type variable. For that I user Random() Method.
- Then get the number from the user.
- Compare that number with the Random number.
- Just use your own logic and limitation of turns and range for the user.
- For score system, you can follow my approach either you can use your own

Random() method is used to pick a random number. Random_number.nextInt(100); here 100 denotes that the random number range will be bounded by 100.

int turn is initialized to zero so that it can count the number of turns user has used to guess the right answer. For each iteration, the value of turn will be increased by 1 as we put turn++ in our loop.

The integer “i” is used to count the turns the user has left to guess the number.

Make A Multiplication Table Using Java Program

Java Program To Make Fibonacci Series With Explanation

**Output:**

Guess a number between 1 to 100, You will have 10 turns! best of luck! 50 Yor Guess is lower than the right guess! Turns left: 9 75 Your Guess Is Higher Than THe Right Guess! Turns left: 8 65 Your Guess Is Higher Than THe Right Guess! Turns left: 7 60 Your Guess Is Higher Than THe Right Guess! Turns left: 6 55 Your Guess Is Higher Than THe Right Guess! Turns left: 5 53 You win! The number was 53 You used 6 turns to guess the right number Your score is 50 out of 100

## Leave a Reply