Game01: A Guessing Game - Exercise

Contact Us or call 1-877-932-8228
Game01: A Guessing Game - Exercise

Game01: A Guessing Game

Duration: 15 to 20 minutes.

Write a program called Game that will ask the user to guess a number and compare their guess to a stored integer value between 1 and 100.

  1. Use a field called answer to store the expected answer.
  2. For now, just hard-code the stored value; we will create a random value later (your code will be easier to debug if you know the correct answer).
  3. Create a method called play() that holds the logic for the guessing. Use the KeyboardReader class to ask for a number between 1 and 100, read the result, and tell the user if they are too low, correct, or too high.
  4. Create a main method, have it create a new instance of Game and call play().

Solution:

Solutions/Game01/Game.java
import util.*;

public class Game {
	private int answer = 67;
	
	public void play() {
		int guess;
		guess = KeyboardReader.getPromptedInt("Enter a number 1 -100: ");
		if (guess < answer) System.out.println("Too low");
		if (guess > answer) System.out.println("Too high");
		if (guess == answer) System.out.println("Correct!");
	}
	
	public static void main(String[] args) {
		new Game().play();		
	}
}

Each of the the three possible cases is tested individually as shown below. All three tests will always be performed. In the next version, we will make the tests mutually exclusive, so that processing stops when one is true. we will use a more efficient approach.

if (guess < answer) System.out.println("Too low");
if (guess > answer) System.out.println("Too high");
if (guess == answer) System.out.println("Correct!");
Next