In: Computer Science
JAVA
Write a number guessing game that will generate a random number between 1and 20 and ask the user to guess that number.
Below is the Java code for mentioned problem statement:
import java.util.Random;
import java.util.Scanner;
public class Main
{ //program will start frome here main function
public static void main(String[] args) {
System.out.print("Application will generate a random
number between 1-20. User has to Guess the number.\nSo lets Play
the game!\n");
Scanner in = new Scanner(System.in);
// Generate random number between 1 to 20
int rand_num = new Random().nextInt(20) + 1;
int count, guess;
String choice;
while (true) {
count = 0;
while (true) {
System.out.print("Enter your guess : ");
// User input
guess = in.nextInt();
count++;
if(guess == rand_num) {
break;
} else if(guess < rand_num) {
System.out.println("Your guess was low, guess again");
} else {
System.out.println("Your guess was high, guess again");
}
}
System.out.println("It took you " + count + " guesses to guess
correctly");
System.out.print("DO you want to try again(yes or no): ");
choice = in.next();
if(choice.equalsIgnoreCase("no")) {
break;
}
}
}
}