A loop is a block of code that executes a set number of times. The developer can dictate how many times it will run based on certain conditions. Bellow you will see the famous song “99 bottles of beer”.  When there are no more bottles of beer, we stop singing.

public class BottlesOfBeer1 {
 public static void main(String[] args)
 {
  int beers = 99;
  String word = " bottles ";
  //Notice that we change the word "bottles" 
  //later for grammatical correctness

  while (beers > 0){
  //We quit when we have no more beer
    if (beers == 1){
      word = " bottle ";
    }
    
    System.out.println(beers + "" + word + " of beer on the wall");
    System.out.println(beers + "" + word + " of beer");
    System.out.println("Take one down");
    System.out.println("Pass it around");
    //we have to subtract a beer, or else the song never ends
    beers--; 
    
    //The final line of each stanza changes based on 
    //condition if there are any more bottles on the wall
    if(beers > 0)
    {
      System.out.println(beers + "" + word + "of beer on the wall");
    }
    else
    {
      System.out.println("No more bottles of beer on the wall!");
    }
  }
 }
}

The code will repeat the phrase over and over, until beers=0 is reached.

A conditional statements come in a few varieties such as if, if/else,  and if/else if/else.

  • An if executes the block of code if the condition in () is met
    • If there are still more beers continue singing
  • An if/else conditional has two blocks, the if and the else blocks
    • The if block is executed if the conditions are met
    • if the conditions are not bet then we execute the else block
  • if/else if/else if the most complex of these conditionals. It executes in sequence, from the first case down to the last one. I will make an example for this type of conditional next time.

 

This example has demonstrate how to use a while loop and the if statement.

See also: do-while statement