Game04: Guessing Game with a Loop - Exercise

Contact Us or call 1-877-932-8228
Game04: Guessing Game with a Loop - Exercise

Game04: Guessing Game with a Loop

Duration: 10 to 20 minutes.


  1. Revise the number guessing program to force the user to guess until they are correct (loop-wise, to keep guessing as long as they are incorrect).
  2. Then add more logic to ask if they want to play again, read a Y or N as their answer, and loop as long as they enter a Y.


import util.*;
import java.util.*;

public class Game {

---- C O D E   O M I T T E D ----
	public void play() {
		int guess;
		do {
			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");
		} while (guess != answer);
	public static void main(String[] args) {
		char playAgain = 'Y';
		do {
			char level = KeyboardReader.getPromptedChar("What level (B, I, A)? ");
			new Game(level).play();		
			playAgain = KeyboardReader.getPromptedChar("Play again (y/n)?: ");
		} while (playAgain == 'Y' || playAgain == 'y');