Write a program that plays the Hi-Lo guessing game with numbers. The program sho
ID: 3926798 • Letter: W
Question
Write a program that plays the Hi-Lo guessing game with numbers. The program should pick a random number between 1 and 100 (inclusive), then repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or chooses to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of guesses and report that value when the user guesses correctly. At the end of each game (by quitting or a correct guess), prompt to determine whether the user wants to play again. Continue playing games until the user chooses to stop.Explanation / Answer
GuessGame.java
import java.util.Random;
import java.util.Scanner;
public class GuessGame {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random r = new Random();
int numOfGuess = 0;
int randNum = r.nextInt(100) + 1;
System.out.println("Please guess the number(-1 to quit): ");
while(true){
int guess = scan.nextInt();
if(guess == -1){
break;
}
numOfGuess++;
if(guess < randNum){
System.out.println("You were low. Please guess again(-1 to quit):");
}
else if(guess > randNum){
System.out.println("You were high. Please guess again(-1 to quit):");
}
else{
System.out.println("Good job! You got the number with "+numOfGuess+" tries.");
numOfGuess = 0;
System.out.println("Would you like to guess another number?(yes/no): ");
String s = scan.next();
if(s.equalsIgnoreCase("no")){
break;
}
else{
randNum = r.nextInt(100) + 1;
System.out.println("Please guess the number(-1 to quit): "); }
}
}
}
}
Output:
Please guess the number(-1 to quit):
45
You were high. Please guess again(-1 to quit):
55
You were high. Please guess again(-1 to quit):
66
You were high. Please guess again(-1 to quit):
33
You were low. Please guess again(-1 to quit):
35
You were low. Please guess again(-1 to quit):
38
Good job! You got the number with 6 tries.
Would you like to guess another number?(yes/no):
yes
Please guess the number(-1 to quit):
55
You were low. Please guess again(-1 to quit):
66
You were high. Please guess again(-1 to quit):
60
You were low. Please guess again(-1 to quit):
63
You were low. Please guess again(-1 to quit):
-1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.