Guess the number:
import java.util.Scanner;
import java.util.Random;
class guessTheNumber{
Scanner s=new Scanner(System.in);
Random r=new Random();
int number;
int attempt=0;
int computerchoice;
public guessTheNumber(){ //constructor which will be automatically executed while creating object
computerchoice=r.nextInt(100);
System.out.println("enter any number");
number=s.nextInt();}
public void play(){
while(computerchoice!=number){//this loop will check whether the number is greater or smallest
attempt++;//this will tell the no of attempt
if(computerchoice<number){
System.out.print("please enter the smaller no:");
number=s.nextInt();
}
else{
System.out.println("please enter the larger no:");
number=s.nextInt();
}
}
attempt++;
System.out.print("completed! in:"+attempt);
}
}
public class rock {
public static void main(String[] args) {
System.out.println("welcome to guess the number game!");
guessTheNumber player1=new guessTheNumber();
player1.play();
}
}
0 Comments