JAVA
Write a number guessing game that will generate a random number between 1and 20 and ask the user to guess that number.
Source Code:
import java.util.Scanner;
import java.util.Random;
class ex
{
public static void main(String[] args) {
Scanner input=new
Scanner(System.in);
Random rand=new Random();
int min=1,max=20;
int count=10,tries=0;
System.out.println("Enter a number
to guess the number between 1 and 20");
int rand_num=(rand.nextInt(max)) +
min ;
int guess=0;
while(count>0)
{
++tries;
--count;
guess=input.nextInt();
if(guess==rand_num)
break;
else
if(rand_num-guess ==2 || rand_num-guess == -2 || rand_num-guess ==1
|| rand_num-guess == -1)
System.out.println("Incorrect, you are very
close to number, you have "+count+" trials remaining");
else
if(guess>rand_num)
System.out.println("Incorrect, your guess is
high and you have "+count+" trials remaining");
else
System.out.println("Incorrect, your guess is low
and you have "+count+" trials remaining");
}
if(count==0)
System.out.println("You reached maximum trials and the number is
"+rand_num);
else
System.out.println("You guessed correctly in "+tries+" tries. The
number is "+rand_num);
}
}
Sample input and output:
Get Answers For Free
Most questions answered within 1 hours.