I am trying to do as many excerises to prepare for an exam, but this one I am st
ID: 3621300 • Letter: I
Question
I am trying to do as many excerises to prepare for an exam, but this one I am stuck!! Can't seem to move forward.Ugh, please help!
The exercise description is this:
Develop a program that plays a guess the number game with the user. The program should generate a random number between 1 and some maximum (such as 100 or 1000), then prompt the user repeatedly to guess the number. When the user guesses incorrectly, the game should give the user a hint about whether the correct answer is higher or lower than the guess. Once the user guesses correctly, the program should print a message showing the number of guesses that user made. Then, the program would ask the user if they would like to play again. The user would respond with a one-word string, like a new game should begin with a user response of an upper or lower case Y. Any other response would stop the game. Once the user chooses not play anymore, the program will give the overall statistics about all the games (total number of games, total guesses, average number of guesses and the best game played (the one with the fewest guesses)).
Explanation / Answer
import java.util.Scanner;
class GuessingGame
{
// statistics
private static int gamesPlayed = 0;
private static int totGuesses = 0;
private static int best = Integer.MAX_VALUE;
private static Scanner kb;
public static void main(String[] args)
{
kb = new Scanner(System.in);
String playAgain = "";
// outer loop: play games
do
{
// play game
int numGuesses = playGame();
// update staistics
totGuesses += numGuesses;
if(best > numGuesses)
{
best = numGuesses;
}
gamesPlayed++;
// ask to play again
System.out.print("Play again? (y/n) ");
playAgain = kb.next();
}
while(playAgain.equalsIgnoreCase("y"));
// display statistics
printStatistics();
}
/**
* Prints statistics about games
*/
private static void printStatistics()
{
System.out.println();
System.out.println("Number of games: "+gamesPlayed);
System.out.println("Total number of guesses: "+totGuesses);
System.out.println("Average number of guesses: "+((double)totGuesses/gamesPlayed));
System.out.println("Best game: "+best+" guesses");
}
/**
* @return the number of guesses to finish the game
*/
private static int playGame()
{
int numGuesses = 0;
// a single game
int number = (int)(Math.random()*100);
int guess = -1;
// ask user to guess until correct
while(true)
{
System.out.print("Enter your guess: ");
guess = kb.nextInt();
// update statistics
numGuesses++;
// feedback
if(guess == number)
{
System.out.println("Correct");
break;
}
else if(guess < number)
{
System.out.println("Too low.");
}
else
{
System.out.println("Too high.");
}
}
return numGuesses;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.