Overview:
Create a Java program that simulates a number guessing game. The computer must randomly choose an integer in the range of 1-10 for the user to guess. The user will then repeatedly input guesses at that number until it is found. After each incorrect guess, the computer will offer output indicating whether a guess was too high or too low to ease the discovery process. The program ends with the computer outputting that the secret number was found, and that the game is over.
Create a class called RandomGuessGame
This class uses the Scanner class for input. Import the Scanner class, as we have practiced in class.
Class variables
Declare a variable userGuess
of type integer. Do not initialize it.
Declare a variable numberToGuess
of type integer. Initialize it to a random integer in the range of 1-10. Use the code / process we have practiced in class.
Create a new Scanner object named userInput
as we have practiced in class.
Methods
public void userGuessesNumber()
Ask the user for their guess. Output the following for the user:
I’m thinking of a number between 1 and 10! Type in your guess!
Note that the output is on two lines. Use the Java newline character for the line break in the output.
(2) Collect the user’s guess and store it.
Use the userInput
object, and execute the proper Scanner class method, to get an integer from the user. The inputted integer must be stored in variable userGuess
.
public void computerChecksAnswer()
Compare the userGuess
variable to the numberToGuess
variable, and output helpful feedback.
Construct the proper Java code using the following pseudo code as a guide.
If the userGuess is greater than the numberToGuess, output “Too High!” Else if the userGuess is less than the numberToGuess, output “Too Low!:
Note that there is no output if the two variables are equivalent.
public void playGame()
Repeatedly ask the user for a guess and have the computer check it, until the number is found. After it is found, the user is congratulated and the game is over.
Construct the proper Java code using the following pseudo code as a guide.
As long as the userGuess and the numberToGuess are not equivalent, Execute the userGuessesNumber and computerChecksAnswer methods over and over
After this code, output to the user:
You got the Secret Number! Game Over!
Note that the output is on two lines. Use the Java newline character for the line break in the output.
Main method
Add a main method to your class.
In the main method create an object from your class RandomGuessGame
. Something like myGame
is fine for the object name.
Execute the playGame()
method to test your project.
Does it work as expected?