Java Programming/Flow control/Loops
Contents |
[edit] Loops
[edit] Introduction to Loops
Loops are a handy tool that enables programmers to do repetitive tasks with minimal effort.
Say we want a program that can count from 1 to 10, we could write the following program.
class Count { public static void main(String[] args) { System.out.println('1 '); System.out.println('2 '); System.out.println('3 '); System.out.println('4 '); System.out.println('5 '); System.out.println('6 '); System.out.println('7 '); System.out.println('8 '); System.out.println('9 '); System.out.println('10 '); } }
The task will be completed just fine, the numbers 1 to 10 will be printed in the output, but there are a few problems with this solution:
- Flexibility, what if we wanted to change the start number or end number? We would have to go through and change them, adding extra lines of code where they're needed.
- Scalability, 10 repeats are trivial, but what if we wanted 100 or even 1000 repeats? The number of lines of code needed would be overwhelming for a large number of iterations.
- More error prone, where there is a large amount of code, one is more likely to make a mistake.
Using loops we can solve all these problems. Once you get you head around them they will be invaluable to solving many problems in programming.
Open up your editing program and create a new file saved as Loop.java
. Now type or copy the following code:
class Loop { public static void main(String[] args) { int i; for (i = 1; i <= 10; i++) { System.out.println(i + ' '); } } }
This code may look confusing to you if you have never encountered a loop before, don't worry, the exact details of different loops will be explained later in this chapter, this is an aid to illustrate the advantages of loops in programming.
If we run the program, the same result is produced, but looking at the code, we immediately see the advantages of loops. 10 lines of code have been reduced to just 4. Furthermore, we may change the number 10 to any number we like. Try it yourself, replace the 10 with your own number.
[edit] While
While loops are the simplest form of loop. The while loop comes in two forms.
The normal while loop repeats a block of code while the specified condition is true. Here is the structure of a while loop:
![]() |
while (<condition>) { // Some code } |
The loop's condition is checked before each iteration of the loop. If the condition is false at the start of the loop, the loop will not be executed at all.
If you want to perform a task a specific number of times, you should use the following algorithm:
![]() |
int i = 0; while (i < <number of iterations>) { // Some code i++; } |
Though you haven't learned about arrays yet, you can iterate through a list or array using this algorithm by replacing <number of iterations>
with array.length
. Then, you can use array[i]
to access the array index at the current iteration.
![]() |
If a loop's condition will never become false, such as if the true constant is used for the condition, said loop is known as an infinite loop. Such a loop will repeat indefinitely unless it is broken out of. Infinite loops can be used to perform tasks that need to be repeated over and over again without a definite stopping point, such as updating a graphics display. |
[edit] Do... while
The do
-while
statement is like the while
, but it will execute a block of code at least once and continue execution as long as the condition is true.
![]() |
do { // Some code } while (<condition>); |
[edit] For
The for
loop provides additional flow control over a while statement. Do you remember the algorithm for looping a certain number of times that was shown earlier? The for loop is like a template version of that.
The for loop consists of the keyword for
followed by three extra statements enclosed in parentheses. The first statement is the variable declaration statement, which allows you to declare one or more integer variables. The second is the condition, which is checked the same way as the while loop. Last is the iteration statement, which is used to increment or decrement variables, though any statement is allowed.
This is the structure of a for
loop:
![]() |
for (<variable declarations>; <condition>; <iteration statement>) { // Code } |
To clarify how a for loop is used, here is an example:
![]() |
for (int i = 1, j = 10; i <= 10; i++, j--) { System.out.print(i + " "); System.out.println(j); } |
This example shows how to iterate with the for statement using multiple variables. It will print the following:
![]() |
1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1 |
Any of the parameters of a for loop can be skipped. Skip them all, and you have an infinitely repeating loop, as such:
![]() |
for (;;) { // Some code } |
[edit] For-each
Arrays haven't been covered yet, but you'll want to know how to use the enhanced for loop, called the for-each
loop. The for-each
loop automatically iterates through a list or array and assigns the value of each index to a variable.
To understand the structure of a for-each
loop, look at the following example:
![]() |
String[] sentence = {"I", "am", "a", "Java", "program."}; for (String word : sentence) { System.out.print(word + " "); } |
The example iterates through an array of words and prints them out like a sentence. What the loop does is iterate through sentence
and assign the value of each index to word
, then execute the code block.
Here is the general contract of the for-each
loop:
![]() |
for (<variable declaration> : <array or list>) { // Some code } |
Make sure that the type of the array or list is assignable to the declared variable, or you will get a compilation error.
[edit] Break and continue keywords
The break
keyword exits a flow control loop, such as a for loop. It basically breaks the loop.
For example, look at the following code:
![]() |
for (int i = 1; i <= 10; i++) { System.out.println(i); if (i == 5) { System.out.println("STOP!"); break; } } |
Normally, the loop would print out all the numbers from 1 to 10, but we have a check for when i
equals 5. When the loop reaches its fifth iteration, it will be cut short by the break
statement, at which point it will exit the loop.
This piece of code will print out:
![]() |
1 2 3 4 5 STOP! |
The continue
keyword jumps straight to the next iteration of a loop and evaluates the boolean expression controlling the loop.
Here is an example of the continue
statement in action:
![]() |
for (int i = 1; i <= 10; i++) { if (i == 5) { System.out.println("Caught i == 5"); continue; } System.out.println(i); } |
This will print out:
![]() |
1 2 3 4 Caught i == 5 6 7 8 9 10 |
[edit] Labels
Labels can be used to give a name to a loop. The reason to do this is so we can break out of or continue with upper-level loops from a nested loop.
Here is how to label a loop:
![]() |
<label name>: <loop> |
To break out of or continue with a loop, use the break
or continue
keyword followed by the name of the loop.
For example:
![]() |
int i, j; int[][] nums = { {1, 2, 5}, {6, 9, 7}, {8, 3, 4} }; Outer: for (i = 0; i < nums.length; i++) { for (j = 0; j < nums[i].length; j++) { if (nums[i][j] == 9) { System.out.println("Found number 9 at (" + i + ", " + j + ")"); break Outer; } } } |
This will print (1, 1)
.
You needn't worry if you don't understand all the code, but look at how the label is used to break out of the outer loop from the inner loop.
[edit] Try... catch statements
The try
-catch
statements are used to catch any exceptions or other throwable objects within the code.
Here's what a try-catch
statement looks like:
![]() |
try { // Some code } catch (Exception e) { // Handle exception here } |
In addition to the try and catch blocks, a finally
block may be present. The finally block is always executed, even if an exception is thrown. It may appear with or without a catch block, but always with a try block.
Here is what a finally block looks like:
![]() |
try { // Some code } catch (Exception e) { // Optional exception handling } finally { // This code is executed no matter what } |
Exception handling isn't going to be covered any time soon, but you should be aware of these constructs.
[edit] Examples
-
public class GetBinary {
-
public static void main(String[] args) {
-
if (args.length == 0) {
-
// Print usage
-
System.out.println("Usage: java GetBinary <decimal integer>");
-
System.exit(0);
-
} else {
-
// Print arguments
-
System.out.println("Received " + args.length + " arguments.");
-
System.out.println("The arguments are:");
-
for (String arg : args) {
-
System.out.println("\t" + arg);
-
}
-
}
-
-
int number = 0;
-
String binary = "";
-
-
// Get the input number
-
try {
-
number = Integer.parseInt(args[0]);
-
} catch (NumberFormatException ex) {
-
System.out.println("Error: argument must be a base-10 integer.");
-
System.exit(0);
-
}
-
-
// Convert to a binary string
-
do {
-
switch (number % 2) {
-
case 0: binary = '0' + binary; break;
-
case 1: binary = '1' + binary; break;
-
}
-
number >>= 1;
-
} while (number > 0);
-
-
System.out.println("The binary representation of " + args[0] + " is " + binary);
-
}
-
}
public class GetBinary { public static void main(String[] args) { if (args.length == 0) { // Print usage System.out.println("Usage: java GetBinary <decimal integer>"); System.exit(0); } else { // Print arguments System.out.println("Received " + args.length + " arguments."); System.out.println("The arguments are:"); for (String arg : args) { System.out.println("\t" + arg); } } int number = 0; String binary = ""; // Get the input number try { number = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { System.out.println("Error: argument must be a base-10 integer."); System.exit(0); } // Convert to a binary string do { switch (number % 2) { case 0: binary = '0' + binary; break; case 1: binary = '1' + binary; break; } number >>= 1; } while (number > 0); System.out.println("The binary representation of " + args[0] + " is " + binary); } }
This is a simulation of playing a game called Lucky Sevens. It is a dice game where the player rolls two dice. If the numbers on the dice add up to seven, he wins $4. If they do not, he loses $1. The game shows how to use control flow in a program as well as the fruitlessness of gambling.
-
import java.util.*;
-
-
public class LuckySevens {
-
public static void main(String[] args) {
-
Scanner in = new Scanner(System.in);
-
Random random = new Random();
-
String input;
-
int startingCash, cash, maxCash, rolls, roll;
-
-
// Loop until "quit" is input
-
while (true) {
-
System.out.print("Enter the amount of cash to start with (or \"quit\" to quit): ");
-
-
input = in.nextLine();
-
-
// Check if user wants to exit
-
if (input.toLowerCase().equals("quit")) {
-
System.out.println("\tGoodbye.");
-
System.exit(0);
-
}
-
-
// Get number
-
try {
-
startingCash = Integer.parseInt(input);
-
} catch (NumberFormatException ex) {
-
System.out.println("\tPlease enter a positive integer greater than 0.");
-
continue;
-
}
-
-
// You have to start with some money!
-
if (startingCash <= 0) {
-
System.out.println("\tPlease enter a positive integer greater than 0.");
-
continue;
-
}
-
-
cash = startingCash;
-
maxCash = cash;
-
rolls = 0;
-
roll = 0;
-
-
// Here is the game loop
-
for (; cash > 0; rolls++) {
-
roll = random.nextInt(6) + 1;
-
roll += random.nextInt(6) + 1;
-
-
if (roll == 7)
-
cash += 4;
-
else
-
cash -= 1;
-
-
if (cash > maxCash)
-
maxCash = cash;
-
}
-
-
System.out.println("\tYou start with $" + startingCash + ".\n"
-
+ "\tYou peak at $" + maxCash + ".\n"
-
+ "\tAfter " + rolls + " rolls, you run out of cash.");
-
}
-
}
-
}
import java.util.*; public class LuckySevens { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random random = new Random(); String input; int startingCash, cash, maxCash, rolls, roll; // Loop until "quit" is input while (true) { System.out.print("Enter the amount of cash to start with (or \"quit\" to quit): "); input = in.nextLine(); // Check if user wants to exit if (input.toLowerCase().equals("quit")) { System.out.println("\tGoodbye."); System.exit(0); } // Get number try { startingCash = Integer.parseInt(input); } catch (NumberFormatException ex) { System.out.println("\tPlease enter a positive integer greater than 0."); continue; } // You have to start with some money! if (startingCash <= 0) { System.out.println("\tPlease enter a positive integer greater than 0."); continue; } cash = startingCash; maxCash = cash; rolls = 0; roll = 0; // Here is the game loop for (; cash > 0; rolls++) { roll = random.nextInt(6) + 1; roll += random.nextInt(6) + 1; if (roll == 7) cash += 4; else cash -= 1; if (cash > maxCash) maxCash = cash; } System.out.println("\tYou start with $" + startingCash + ".\n" + "\tYou peak at $" + maxCash + ".\n" + "\tAfter " + rolls + " rolls, you run out of cash."); } } }