Write a Java class that provides methods to play a guessing
Solution
Please follow the code and comments for description :
CODE :
public class GuessingGame { // class to run the code
int integerToGuess; // instance variables
int numberOfGuesses;
boolean correctGuessReceived;
int guessApprox;
public GuessingGame(int intToGuessIn, int numOfGuessesIn, boolean correctGuessIn) { // constructor to get the data
integerToGuess = intToGuessIn;
numberOfGuesses = numOfGuessesIn;
correctGuessReceived = correctGuessIn;
}
//integerToGuess = (100 * Math.random());//identifier expected?
public int guess(int userGuess) { // method to guess the value the user given
if (userGuess < integerToGuess) {
guessApprox = -1; //guess is too low
} else if (userGuess > integerToGuess) {
guessApprox = 1; //guess is too high
} else {
guessApprox = 0; //guess is correct
}
return guessApprox;
}
public int getNumberOfGuesses() { // method to return the number of guesses
return numberOfGuesses;
}
public boolean gameIsComplete() { // method that checks if the game is done or not
correctGuessReceived = false;
if (guessApprox == 0) {
correctGuessReceived = true;
}
return correctGuessReceived;
}
public void reset() { // method to reset the values
integerToGuess = 0;
numberOfGuesses = 0;
correctGuessReceived = false;
}
public static void main(String[] args) { // temporary main driver method
GuessingGame gg = new GuessingGame(1, 5, true); // passing the values to the constructor
System.out.println(\"Guess Approx Value : \"+gg.guess(1)); // checking the result of the guess
System.out.println(\"Result? \"+gg.gameIsComplete()); // check if the result is winor loss
}
}
OUTPUT :
Case 1 :
Guess Approx Value : 0
Result? true
Case 2 :
Guess Approx Value : 1
Result? false
Description :
Here the glitch is that the value (guessApprox) that we use for the guess value checking is a local variable to the method so that cannot be used in the other methods, but we have used in the method gameIsComplete to check if the game is completed or not which is not accessible by the method that results in a compilation error. To over come this we need to make the variable global or an intanse variable so that the value could be found anywhere in the class.
If this is not the case the we need to call the mathod to get the guessApprox value in the main method and then check for the game is a win or not by passing the same value to the gameIsComplete method, and thus changes the method signature.
Hope this is helpful.

