While loops

Sometimes we will want to run a piece of code until a condition is met, and we can do that in Java. Consider the lyrics for the ten green bottles song we worked with in some of the earlier tasks, at that time we simply printed the lyrics for one verse, and it would be have been rather tedious to print all the verses by hand - more so if we decided to start at 100 green bottles.

Rather than having lots of code, it would be better to keep track of the number of bottles on the wall, and while there are more than zero, keep printing the song, but replace the existing string for the number with a variable. This is known as a 'While' loop

The syntax for a while loop takes the following form:

while (conditionIsMet) {
    //do something
}

To convert the 10 green bottles code, we need to make some changes. Here is the original code:

String wallPhrase = " green bottles hanging on the wall";
System.out.print("10" + wallPhrase + ",");
System.out.print("10" + wallPhrase + ",");
System.out.print(" and if one green bottle should accidentally fall, there'd be ");
System.out.println("9" + wallPhrase);

Firstly, we will create a variable to hold the number of bottles, and replace the lines that print 10 (and 9) as a string, so they print the variable. We will also reduce the variable by one for the final line as follows:

int noOfBottles = 10;
String wallPhrase = " green bottles hanging on the wall";
System.out.print(noOfBottles + wallPhrase + ",");
System.out.print(noOfBottles + wallPhrase + ",");
System.out.print(" and if one green bottle should accidentally fall, there'd be ");
noOfBottles -= 1;
System.out.println(noOfBottles + wallPhrase);
We are taking advantage of one of Java's features here that allows us to append an integer (as text) to a string - rather than resulting in an Error, Java knows that we cannot numerically add a number to a string, so it automatically converts the noOfBottles value to a String for us.

Add the code in the listing above to a new Java command line application and run it to check it works

The next stage is to repeatedlty execute the code until we have run out of bottles

Add a while loop around the code that prints the song, making sure that the variable that keeps track of the number of bottles is not inside the loop, as follows:

int noOfBottles = 10;
while (noOfBottles > 0) {
    String wallPhrase = " green bottles hanging on the wall";
    System.out.print(noOfBottles + wallPhrase + ",");
    System.out.print(noOfBottles + wallPhrase + ",");
    System.out.print(" and if one green bottle should accidentally fall, there'd be ");
    noOfBottles -= 1;
    System.out.println(noOfBottles + wallPhrase);
}

Modify the code in your programme to match that shown above

Ensuring the loop can exit

At this point it is imperative to understand that in the above example (and similar style while loops) the code inside the loop must affect a value outside the loop so the loop can eventually cease. In this case, it is the line of code that reduces the value of noOfBottles by one that ensures that eventually the code can cease executing (because noOfBottles eventually gets to zero)

Infinite loops

If code is written such that a loop cannot exit, then it will likely cause undesired results, the application may run out of memory, and crash, or it may continue indefinately. If a loop is continuing due to a coding error and you need it to stop, press the red stop button to the left of the output window, or click 'Run' and then 'Stop' on the menu.

Task

Write 'While' loops to perform the following tasks (and you should devise each solution yourself)

  1. Output all the numbers from 1 to 100
  2. Output the Fibonacci sequence of numbers, up to and including 144 - hint you will likely need two variables declared outside of the loop
  3. Modify the Fibonacci sequence so the initial numbers are 1 and 3. Verify the highest number found below 144 is 123.
  4. Output all the lowercase letters from 'a' to 'z'. Determining how to do this will require independent research (or some crafty guesswork)

Breaking out of a loop

Sometimes we may need to break out of a loop other than when some value is reached as a natural process of the loop. This might be as a result of user input

To exit a loop simply requires the break keyword to be used. If we place this at the end of one of the example loops above as follows

break;
it would only iterate once, which would defeat the purpose of the loop, so instead we might ask the user if they wish to continue (getting the response using the scanner), and if that is met, break out of the code.

Task

  1. In a new command line project write code to prompt the user to type '1' to continue.
  2. Add another line to read their example into an Int variable
  3. Write an if statement that prints a message saying "Finished" if the user has not typed 1
  4. Adapt the code you've written, placing it inside the 10 green bottles loop code, so that the user can choose to have the next verse output.

Further tasks

  1. The continue keyword can also be used inside a loop. Identify what this keyword does and try and identify a specific example where it might be useful
  2. The ten green bottles programme has an issue whereby the final verse states "1 green bottles" Within the loop, write code so that when there is only one bottle hanging on the wall, the singular 'bottle' is output.