Question
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
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.
In Java
Here is the code that needs to be modify.
import java.util.*;
public class Guess {
public static void main(String[] args) { /** * Get a random number between 1 to 1000 */ int expected = 1 + (int) (Math.random() * 1000); Scanner scan = new Scanner(System.in); /** * Run an infinite loop until the game ends. */ while (true) { /** * Entering the guessed input */ System.out.print("Guess a number between 1 and 1000. : "); int guess = scan.nextInt(); /** * If the guessed number is same as expected */ if (guess == expected) { System.out.println("Congratulations. You guessed the number!"); System.out.println("Would you like to play again? (Y/N) : "); String option = scan.next(); // entering whether user wants to play again /** * If users want to play again change the random number */ if (option.equals("Y") || option.equals("y")) { expected = 1 + (int) (Math.random() * 1000); } /** * If user wants to quit break the infinite loop */ else { System.out.println("Good Bye!"); break; } } /** * If guessed number is less than expected */ else if (guess < expected) { System.out.println("Too low. Try again."); } /** * If number is greater than expected */ else { System.out.println("Too high. Try again."); } } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started