Guess the number in java

 Number guessing game in Java

The task is to write a Java program in which a user will get K trials to guess a randomly generated number. Below are the rules of the game:

  • If the guessed number is bigger than the actual number, the program will respond with the message that the guessed number is higher than the actual number.
  • If the guessed number is smaller than the actual number, the program will respond with the message that the guessed number is lower than the actual number.
  • If the guessed number is equal to the actual number or if the K trials are exhausted, the program will end with a suitable message.

Approach: Below are the steps:

  • The approach is to generate a random number using random number generator in Java.
  • Now using a loop, take K input from the user and for each input print whether the number is smaller or larger than the actual number.
  • If within K trials the user guessed the number correctly, print that the user won.
  • Else print that he was not able to guess and then print the actual number.

Below is the implementation of the above approach:

 package com.ritesh;
import java.util.Random;
import java.util.Scanner;

class game{
public int inputNumber;
public int number;
public int noOfGusses=0;

private int getNoOfGusses(){
return getNoOfGusses();

}

public void setNoOfGusses(int noOfGusses) {
this.noOfGusses = noOfGusses;
}


game(){
Random num=new Random();
this.number=num.nextInt(100);

}
void takeUserInput(){
System.out.println("Gusses the number");
Scanner sc=new Scanner(System.in);
inputNumber = sc.nextInt();
}
boolean isCorrectOrNot(){
noOfGusses++;

if(inputNumber==number){
System.out.format("Yes you are right it was %d\n and you gusses in %d",number,noOfGusses);
System.out.println("Correct");
return true;
}
else if(inputNumber<number){
System.out.println("Smaller input");
}
else if(inputNumber>number){
System.out.println("Bigger input");
}
return false;

}


}

public class kam {
public static void main(String[] args) {
game game=new game();

boolean b=false;
while (!b){
game.takeUserInput();
b= game.isCorrectOrNot();
System.out.println(b);
}
}
}

Comments