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
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)
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.
Write 'While' loops to perform the following tasks (and you should devise each solution yourself)
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.
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