A Problem Solved: A Guessing Game

In this lesson, we will write a guessing-game program that uses a while loop.

Problem statement

Vanessa used to play a guessing game with her grandfather. He would think of an integer from 1 to 100, and she would try to guess it. He would tell her whether her guess was correct, too high, or too low. She would continue guessing in this way until she guessed correctly. Write a Java program that plays this game, taking the role of Vanessa’s grandfather.

A pseudocode solution

The logic of the guessing game can be described by the following pseudocode:

myInteger = a random integer in the range 1 to 100
guess = player’s initial guess
while (guess is incorrect)
{
   Tell player whether guess is too high or too low
   guess = player’s next guess
}
Tell player that the last guess was correct

The program

The program given below implements the previous pseudocode. Try running it.

Get hands-on with 1400+ tech skills courses.