top of page
Search
Writer's pictureSiah Peih Wee

Using Java While Loop

Updated: Sep 26, 2022

In this article you will see how a while loop is being used in a game call Jelly Beans.


First of all, you can reference to the code written as we explain part by part of it.


Click on the [Run] button below to play the game.


Let's first take a look at the sequence in main function. if you read line by line, you can see the sequence how the game is being shown to the player.

public static void main(String[] args) 
{
    generateBeans();

    boolean bPlaying = true;
    while (bPlaying) 
    {
      clearScreen();
      showInstructions();

      int iLeft = displayJar();
      if(iLeft > 0)
      {
        //show current player and instructions
  
        boolean bGotInt = false;
        while (!bGotInt) 
        {
          try 
          {
            //get user input
            bGotInt = true;
          } 
          catch (Exception e) 
          {
            //catch exception
          }
        }
  
        //determine who is the next player
      }
      else
      {
        //show game over and who wins.
        bPlaying = false;
      }
    }
  }

After the generating beans, the program will use a while loop to repeat until the game is not longer playing.

boolean bPlaying = true;
while (bPlaying) 
{
   //keep looping until game ends
}

There is another while loop that keep checking if player has keyed in an integer.

boolean bGotInt = false;
while (!bGotInt) 
{
   try 
   {
      //get user input
      bGotInt = true;
   } 
   catch (Exception e) 
   {
      //catch exception
   }
}

Noticed both will loop till the condition is no long valid.

55 views0 comments

Comments


Post: Blog2 Post
bottom of page