The while loop

The while loop is, at least syntactically, the simplest of the loops. We define it as:

while ( condition ) {
      body
}

where

  • condition is a boolean expression;
  • body is zero or more statements;
  • The while loop executes the code in body as long as the condition expression evaluates to true, evaluating condition before each execution of body.

You would typically use a while loop when there are an indeterminate number of iterations of the loop. The “game cycle” that we introduced in Section 2.2 (Grounding—The Game Cycle), is a good example.

The Game Cycle

This loop executes as long as the game is not over. We might model a very simple Rock-Paper-Scissors game, where the player plays against the computer, and the first one to win two tries wins, as follows:

public class RockPaperScissorsGame {
   public void play() {
      int playerScore = 0;
      int computerScore = 0;
      int numGames = 0;
      
      while (numGames < 3) {
      
         RPSChoice playerChoice = getPlayerChoice();
         RPSChoice computerChoice = getComputerChoice();
         RPSOutcome outcome = determineOutcome(playerChoice, computerChoice);
         if (outcome == RPSOutcome.Player1) {
            playerScore++;
            numGames++;
         } else if (outcome == RPSOutcome.Player2) {
            computerScore++;
            numGames++;
         } else {
            // a tie, so don't increment numGames
            continue;
         }
    
      } // end while
    
   }
    
   private RPSChoice getPlayerChoice() {
      ... // omitted--not important right now
   }
   private RPSChoice getComputerChoice() {
      ... // omitted--not important right now
   }
   private RPSOutcome determineOutcome(RPSChoice player1Choice, 
                                       RPSChoice player2Choice) {
      ... // omitted--not important right now
   }
}
    
enum RPSChoice { Rock, Paper, Scissors }
enum RPSOutcome { Player1, Player2, Tie }

Note the // end while comment. Comments like these help you keep your curly braces straight.