Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

6.30 (Guess the number) Write an application that plays \"guess the number\" as

ID: 3767701 • Letter: 6

Question

6.30 (Guess the number) Write an application that plays "guess the number" as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The application displays the prompt "Guess a number between 1 and 1000". The player inputs a first guess. If the player's guess is incorect, your program should display "Too high. Try again". or "Too low. Try again.". to help the player zero in on the correct answer. The program should prompt the user for the next guess. When the user enters the correct answer, display "Congratulations! You guessed he number!" and allow the user to choose whether to play again. (Note: The guessing technique employed in this problem is similar to binary search, which is discussed in Chapter 19, Searching, Sorting and Big O.

6.31 Guess-the-Number Game Modification: Modify the program of Exercise 6.30 above to count the number of guesses the player makes. If the number is 10 or fewer, print "Either you know the secret or you got lucky!" If the player guesses the number in 10 tries, then print "Ahah! You know the secret!" If the player makes more than 10 guesses, then print “You should be able to do better!" Why should it take no more than 10 guesses? Well, with each “good guess” the player should be able to eliminate half of the numbers, then half of the remaining numbers, and so on.

Explanation / Answer

Here is the code for you. If you have any queries, just get back to me.

import java.io.*;
import java.util.*;
class GuessGame
{
public static void main(String[] args)
{
while(true)
{
Random rand = new Random();
int number = rand.nextInt(1000) + 1;
int guessCount = 0;
System.out.print("I'm ready with a number. Guess it... ");
Scanner sc = new Scanner(System.in);
int guess = sc.nextInt();
guessCount++;
while(guess != number)
{
if(guess < number)
System.out.println("Too low. Try again.");
else
System.out.println("Too high. Try again.");
guess = sc.nextInt();
guessCount++;
}
System.out.println("Congratulations! You guessed he number!");
if(guessCount < 10)
System.out.println("Either you know the secret or you got lucky!");
else if(guessCount == 10)
System.out.println("Ahah! You know the secret!");
else
System.out.println("You should be able to do better!");
System.out.print("Do you want to play again. Y for yes: ");
char again = sc.next().charAt(0);
if(again != 'y' && again != 'Y')
break;
}
}
}