Search This Blog

Friday, May 28, 2021

'Guess the number game' source code(java)

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


class game{
Random ra=new Random();
Scanner sc=new Scanner(System.in);
int theNum= ra.nextInt(100);

public void cond(int l){

for (int i=1;i<=l;i++){
System.out.println(" "+i);
System.out.print("Enter your number: ");
int a=sc.nextInt();

if (theNum>a){
System.out.println("Greater than "+a);
}

else if (theNum<a){
System.out.println("Less than "+a);
}

else {
System.out.println("Congrats !!!"+theNum+" is the correct guess");

if (i<=6)
System.out.println("It took you only "+i+" tries to guess the number");

else {
System.out.println("But it took you "+i+" tries");
}
break;
}
System.out.println(" ");
if (i==l){
System.out.println("Loser!!!");
System.out.println("The number is "+theNum);
}
}

}
}


public class Guess_the_number_game {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
// Create a class game which allows the user to play " Guess the number" game once
game guess=new game();
System.out.println("Choose your difficulty level (1-Easy,2-Medium,3-Hard):");
int k=sc.nextInt();
System.out.println("Guess the number");
System.out.println("The number is between 0 and 100");
if (k==1){
System.out.println("You will be given 10 chances to guess the number");
guess.cond(10);
}
else if (k==2){
System.out.println("You will be given 7 chances to guess the number");
guess.cond(7);
}
else if (k==3){
System.out.println("You will be given 5 chances to guess the number");
guess.cond(5);
}

}
}