Create a simple game in which the user is prompted to guess a value between 1 an
ID: 3792677 • Letter: C
Question
Create a simple game in which the user is prompted to
guess a value between 1 and 100. The user should continually be prompted
until he or she guesses the number. The number of guesses should be tracked
and the user should be given a hint if the next guess should be higher or lower
than the last guest.
Started code is provided on Blackboard or you may use the following code. The
name of the class should be ImprovedGuessingGame. The name of the project
can be Lab5-ImprovedGuessingGame.
Make sure that your code implements the sample interaction below.
import java.util.Scanner; import java util Random; public class ImprovedGuessingGame f public static void main(Stringl args) Scanner scanner new Scanner (System.in); Random randGen new Random(); int secretValue randGen.nextInt(99) 1; Step 1: Initialize a guess count and currentGuess Step 2: Until the guess is correct, prompt the user for a guess, check it, give some feedback and update the count Step 3: Display the number of guesses neededExplanation / Answer
ImprovedGuessingGame.java
import java.util.Random;
import java.util.Scanner;
public class ImprovedGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randGen = new Random();
int secretValue = randGen.nextInt(99)+1;
int currentGuess = 0;
System.out.print("Guess a number between 1 and 100: ");
int guess = scanner.nextInt();
while(guess != secretValue){
currentGuess++;
if(guess < secretValue){
System.out.print("Your guess was too low. Try again!. Provide another guess for the number: ");
}
else{
System.out.print("Your guess was too high. Try again!. Provide another guess for the number: ");
}
guess = scanner.nextInt();
}
System.out.println("Great! You guessed the number in "+currentGuess+" tries.");
}
}
Output:
Guess a number between 1 and 100: 44
Your guess was too high. Try again!. Provide another guess for the number: 66
Your guess was too high. Try again!. Provide another guess for the number: 33
Your guess was too high. Try again!. Provide another guess for the number: 11
Your guess was too low. Try again!. Provide another guess for the number: 22
Your guess was too high. Try again!. Provide another guess for the number: 15
Your guess was too low. Try again!. Provide another guess for the number: 18
Your guess was too high. Try again!. Provide another guess for the number: 16
Your guess was too low. Try again!. Provide another guess for the number: 17
Great! You guessed the number in 8 tries.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.