Computer Program Reading Comprehension Project
U of T Computer Program Reading Comprehension Project
Guessing Game
This class allows the user to play a simple guessing game. It is the solution to an assignment given out in the fall of 2003. The relevant part of the original assignment follows.

Write a class GuessingGame that allows a user to play a number-guessing game. The constructor takes the integer to be guessed. Instance method play first prompts the user with
"Guess an integer."
and then displays a series of prompts, which are one of these two, as appropriate:
"Your guess was too high. Guess again."
"Your guess was too low. Guess again."
When the user finishes, tell them
"You're right!"
using JOptionPane.showMessageDialog. You'll need to give this method null as the first argument, and the message as the second.

Also, write
import javax.swing.*;
instead of
import javax.swing.JOptionPane;
because of a nuance of our automarking.

Download files: GuessingGame.java
Areas: User input and output.


GuessingGame.java
1import javax.swing.*;
2
3/** A game for guessing a number. */
4public class GuessingGame {
5
6  /** The number to be guessed. */
7  private int solution;
8
9  /**
10   * A GuessingGame with solution n.
Displaying 10 of 35 lines
View full source


Question 1
Which comments will be part of the output from javadoc?
Hints Solution

Question 2
What happens if the user enters a string that is not an integer?
Hints Solution

Question 3
What happens if the user just presses "Enter"?
Hints Solution

Question 4
Is there any place where the indenting does not reflect the nesting of the control structures?
Solution

Question 5
Why does this appear in line 14,
this.solution= n;
but not in line 25,
while (Integer.parseInt(guess) != solution) {
Solution

Question 6
How would you change the class-specification to eliminate the need for the instance variable solution?
Hints Solution

Question 7
How could you make the play method more efficient?
Hints Solution

Question 8
Can you suggest any ways to make the code for the GuessingGame class more readable?
Solution

Question 9
What happens if play is called twice in a row? Can you suggest a situation where this would be helpful?
Solution

Question 10
Is there any way for the user/guesser to cause this code to crash?
Solution

Question 11
Where is solution initialized?
Solution

Question 12
When is solution initialized?
Solution

Question 13
Is it possible for the play method to be called without initializing the solution instance variable first?
Solution

Question 14
Can the same instance be used to guess two different numbers?
Solution

Question 15
How would you change the class so that an instance can be reused to play the game repeatedly with different numbers.
Hints Solution

Question 16
What is the largest number that the player might guess? The smallest?
Hints Solution