Game02: A Revised Guessing Game - Exercise

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

Game02: A Revised Guessing Game

Duration: 10 to 15 minutes.
  1. Revise your number guessing program to use if . . . else logic (you can test for too low and too high, and put the message for correct in the final else branch).
  2. Once you have done that, here is a way to generate a random answer between 1 and 100:
    1. At the top:
      import java.util.*;
    2. Add a private field for a random number generator:
      private Random r = new Random();
    3. Then, you can initialize the answer field:
      answer = r.nextInt(100) + 1;
      the nextInt(int n) method generates a number greater than or equal to 0 and less than n, so r.nextInt(100) would range from 0 through 99; we need to add 1 to raise both ends of the range.
    4. You might want to print the expected correct answer to aid debugging.

Note that until we cover looping, there will be no way to truly "play" the game, since we have no way to preserve the value between runs.

Solution:

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

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