Write a Java program to play the \"hi-Lo\" game. You can put all the code in one
ID: 3585060 • Letter: W
Question
Write a Java program to play the "hi-Lo" game. You can put all the code in one class with a "main" method. The program will generate a random integer in the range of 1 to 100 and ask the user to guess the integer If the user's guess is higher than the generated number you will tell the user and ask the user to guess again. If the user's guess is lower than the generated number you will tell the user and ask the user to guess again. Continue this until the user guesses the correct number and congratulate the user.
Keep the code as simple as possible
Explanation / Answer
GuessingGame.java
import java.util.Random;
import java.util.Scanner;
public class GuessingGame{
public static void main(String[] args) {
//Declaring variables
int secret, guess;
//Creating the Random class object
Random generator = new Random();
// Scanner object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
//This loop will continue to execute until the user enters either 'Y' or 'y'
while (true) {
//generating the random number
secret = generator.nextInt((100 - 1) + 1) + 1;
//this loop continues to execute until the user correctly guesses the number;
while (true) {
//Getting the user guess entered by the user
System.out.print("Guess the number (Between 1-100):");
guess = sc.nextInt();
if (guess == secret) {
System.out.println("** Congratulations your guess is correct **");
break;
} else {
if (guess > secret) {
System.out.println("** Higher **");
continue;
} else {
System.out.println("** Lower **");
continue;
}
}
}
// Getting the character from the user 'Y' or 'y' or 'N' or 'n'
System.out.print(" Do you want to Play Again(Y/N) ::");
char ch = sc.next(".").charAt(0);
if (ch == 'Y' || ch == 'y')
continue;
else {
System.out.println(":: Thanks for playing the game. ::");
break;
}
}
}
}
_____________________
Output:
Guess the number (Between 1-100):50
** Lower **
Guess the number (Between 1-100):75
** Lower **
Guess the number (Between 1-100):90
** Lower **
Guess the number (Between 1-100):95
** Lower **
Guess the number (Between 1-100):98
** Lower **
Guess the number (Between 1-100):100
** Higher **
Guess the number (Between 1-100):99
** Congratulations your guess is correct **
Do you want to Play Again(Y/N) ::N
:: Thanks for playing the game. ::
_____________Could you rate me well.Plz .Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.