this is a program allows the user to play a game in which the program thinks of
ID: 3540218 • Letter: T
Question
this is a program allows the user to play a game in which the program thinks of a random integer and accepts guesses from the user until the user guesses the number correctly. After each incorrect guess, you will tell the user whether the correct
answer is higher or lower.
A new game should begin if the user's response starts with a lower- or upper-case Y. For example, answerssuch as "y", "Y", "yes", "YES", "Yes", or "yeehaw" all indicate that the user wants to play again. Any other response means that the user does not want to play again. For example, responses of "no", "No", "okay", "0", "certainly", and "hello" are all assumed to mean no.Once the user chooses not to play again, the program.prints overall statistics about all games.
the output should be like this
I'm thinking of a number between 1 and 5...
Your guess? 2
It's higher.
Your guess? 4
It's lower.
Your guess? 3
You got it right in 3 guesses!
Do you want to play again? y
I'm thinking of a number between 1 and 5...
Your guess? 3
It's lower.
Your guess? 2
You got it right in 2 guesses!
Do you want to play again? n
Overall results:
Total games = 4
Total guesses = 12
Guesses/game = 3.0
Best game = 2
the problem i met is how to make the game method repeat by enter the answer to "DO YOU WANT TO PLAY AGAIN"
thank you very much if you can give the specific codes!
Explanation / Answer
please rate - thanks
I wan't sure about a few things, so if you need any changes, just tell me what they are, and I'll do them
import java.util.*;
public class GuessANumber
{
public static void main(String [] args)
{Scanner in=new Scanner(System.in);
Random r = new Random();
int num,games=0,totalGuesses=0,bestScore=0,bestGame=0;
int guess,guesses;
char choice;
boolean gameOver;
do
{System.out.println("I'm thinking of a number between 1 and 5...");
num=r.nextInt(5)+1;
guesses=0;
gameOver=false;
do
{System.out.print("Your guess? ");
guess=in.nextInt();
guesses++;
if(guess>num)
System.out.println("It's lower");
else if(guess<num)
System.out.println("It's higher");
else
{System.out.println("You got it right in "+guesses+" guesses!");
games++;
totalGuesses+=guesses;
gameOver=true;
if(games==1)
{bestGame=games;
bestScore=guesses;
}
else
if(guesses<bestScore)
{bestGame=games;
bestScore=guesses;
}
}
}while(!gameOver);
System.out.print("Do you want to play again? ");
}while(Character.toUpperCase(in.next().charAt(0))=='Y');
System.out.println(" Overall results:");
System.out.println("Total games = "+games);
System.out.println("Total guesses = "+totalGuesses);
System.out.println("Guesses/game = "+totalGuesses/(double)games);
System.out.println("Best game = "+bestGame);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.