Site icon DataFlair

Java Project – Number Guessing Game

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Program 1

// Number Guess  Game
import java.util.Scanner;
import java.util.Random;
    
class NumberGuess
{
     public static void main(String[] args) 
    {
        try
        {
            Scanner scan=new Scanner(System.in);
            Random random=new Random();
            int compchoice,userchoice;
            String choice;

         do
        {    
            compchoice=random.nextInt(100);
            //System.out.println(compchoice);
            System.out.println("-------------Number Guess Game----------------------");
            int count=5;
            int i=0;
            while(true)
            {
                  System.out.println("Enter a number for guess: ");
                  userchoice=scan.nextInt();
                   i++; 
                   count--; 
                   if(userchoice==compchoice)
                   {
                     System.out.println("Congrats you won the game....! in "+ i + " chance");
                     break;
                   }
                   else 
                   if(userchoice>compchoice)
                   System.out.println("Your number is greater than system. "+ count +" chance left");
                   else
                   System.out.println("Your number is less than system. "+ count +" chance left");
                
                 if(count==0)  
                { 
                   System.out.println("Opps you lose the game... chances is over");
                   System.out.println("Correct Number is : " + compchoice);
                   break;
                }  
            }
            System.out.println("do you want to play more....(yes/no)");
            choice=scan.next().toLowerCase();
           }while(choice.equals("yes"));       
        } 
        catch(Exception e)
        {
            System.out.println(e);
        }
     System.out.println("Thanks for playing .... Bye Bye");
    }
}

 

Exit mobile version