Answer:
import java.util.Scanner;
import java.util.Random;
public class Hi_Lo {
// Create a scanner object to read from the keyboard
static Scanner kb = new Scanner(System.in);
// Create a Random object to be used to generate random numbers
static Random rand = new Random();
// This is the main method
public static void main(String[] args) {
// Call the playGame() method
playGame();
}
public static void playGame() {
// Generate a random number between 1 and 100 both inclusive
// Store the value in an int variable, num
int num = rand.nextInt(100) + 1;
// Create and initialize a variable to hold the user's guess
int guess = 0;
// Create and initialize a variable to hold the number of guesses
int guesses = 0;
// Create an infinite do while loop that keeps looping until a certain condition
// is reached.
do {
// Prompt the user to enter a number between 1-100
System.out.println("Guess what number I have (1-100)? ");
// Store the user input in the guess variable
guess = kb.nextInt();
// Increment guess by one
guesses++;
// Check if the user's guess (guess) is greater than, less than or equal to the
// generated random number (num).
// If it is greater or lower, ask the user to try again.
// If they are equal, display how many times they guessed and ask if they want
// to play again.
if (guess > num) {
System.out.println("Too high, try again.");
} else if (guess < num) {
System.out.println("Too low, try again.");
} else {
System.out.println("You're right, the number is " + num);
System.out.println("You guessed " + guesses + " times");
// Ask the user if they want to play again
// If yes, recursively call the playGame method again
// Otherwise, break out of the loop.
// Make sure the user's input is treated as case insensitive by using the
// equalsIgnoreCase method.
// The user can type yes, no, y or n. Case does not matter.
System.out.println("Do you want to play again? (Y or N)");
String answer = kb.next();
if (answer.equalsIgnoreCase("Yes") || answer.equalsIgnoreCase("Y")) {
playGame();
} else {
System.out.println("Game aborted. Thanks for your time");
break;
}
}
} while (true);
}
}
Answer has also been attached to this response as a source code file. Please download the file for more readability.
Explanation:
The code contains comments explaining every segment of the code. Kindly download the file and go through the comments in the code.
Hope this helps!