break and continue


Iteration Statements

Iteration statements provide the capability to execute one or more program statements repeatedly based on the results of an expression evaluation. There are three flavors of iteration statement: while, do/while, and for. These statements are discussed in detail in this section. Iteration statements are also referred to as loops. So, when you hear another programmer talking about a for loop, while loop, or do loop, they are referring to the iteration statements.

while Statement

The while statement will repeat one or more program statements based on the results of an expression evaluation. Figure 7-12 shows the execution diagram for the while statement.

image from book
Figure 7-12: while Statement Execution Diagram

Personality of the while Statement

The while statement has the following personality:

  • It will evaluate the expression before executing its body statements or code block

  • The expression must eventually evaluate to false or the while loop will repeat forever (Sometimes, however, you want a while loop to repeat forever until some action inside it forces it to exit.)

  • The expression might evaluate to false and therefore not execute its body statements

Essentially, the while loop performs the expression evaluation first, then executes its body statements. Somewhere within the while loop a program statement must either perform an action that will make the expression evaluate to false when the time is right or explicitly force an exit from the while loop.

Example 7.9 shows the while statement in action. Figure 7-13 gives the results of running this program.

Example 7.9: WhileStatementTest.java

image from book
 1    public class WhileStatementTest { 2       public static void main(String[] args){ 3          int int_i = 0; 4 5          while(int_i < 10){ 6            System.out.println("The value of int_i = " + int_i); 7            int_i++; 8          } 9       } 10   }
image from book

image from book
Figure 7-13: Results of Running Example 7.9

Referring to example 7.9 — on line 3 the integer variable int_i is declared and initialized to 0. The variable int_i is then used in the while expression and is compared to the integer literal value 10. So long as int_i is less than 10 the statements contained within the body of the while loop will execute. (That includes all statements between the opening brace appearing at the end of line 5 and the closing brace on line 8.) Notice how the value of int_i is incremented with the ++ operator. This is an essential step because if int_i is not incremented the expression will always evaluate to true which would result in an infinite loop. (Note: Apple, Inc. headquarters are located at 1 Infinite Loop, Cupertino, CA 95014)

do/while Statement

The do/while statement will repeat one or more body statements based on the result of an expression evaluation. The do/while loop is different from the while loop in that its body statements are executed at least once before the expression is evaluated. Figure 7-14 gives the execution diagram for a do/while statement.

image from book
Figure 7-14: do/while Statement Execution Diagram

Personality of the do/while Statement

The do/while statement has the following personality:

  • It will execute its body statements once before evaluating its expression

  • A statement within its body must take some action that will make the expression evaluate to false or explicitly exit the loop, otherwise the do/while loop will repeat forever (Like the while loop, you may want it to repeat forever.)

  • Use the do/while loop if the statements it contains must execute at least once

So, the primary difference between the while and do/while statements is where the expression evaluation occurs. The while statement evaluates it at the beginning — the do/while statement evaluates it at the end. Example 7.10 shows the do/while statement in action. Figure 7-15 shows the results of running this program.

Example 7.10: DoWhileStatementTest.java

image from book
 1    public class DoWhileStatementTest { 2      public static void main(String[] args){ 3        int int_i = 0; 4 5        do { 6           System.out.println("The value of int_i = " + int_i); 7           int_i++; 8           } while(int_i < 10); 9      } 10   }
image from book

image from book
Figure 7-15: Results of Running Example 7-10

Referring to example 7.10 — on line 3 the integer variable int_i is declared and initialized to 0. The do/while statement begins on line 5 and its body statements are contained between the opening brace appearing at the end of line 5 and the closing brace on line 8. Notice that the while keyword and its expression are terminated with a semicolon.

for Statement

The for statement provides the capability to repeat a set of program statements just like the while loop and the do/ while loop. However, the for loop provides a more convenient way to combine the actions of counter variable initialization, expression evaluation, and counter variable incrementing. Figure 7.16 gives the execution diagram for the for statement.

image from book
Figure 7-16: for Statement Execution Diagram

How The for Statement is Related to the While Statement

The for statement is more closely related to the while statement than to the do/while statement. This is because the for statement’s middle expression (i.e., The one used to decide whether or not to repeat its body statements.) is evaluated before the body statements are executed.

Personality of the for Statement

The for statement has the following personality:

  • Provides a convenient way to initialize counting variables, perform conditional expression evaluation, and increment loop-control variables

  • The conditional expression is evaluated up front just like the while statement

  • The for statement is the statement of choice to process arrays (You will become an expert at using the for statement in chapter 8)

Example 7.11 shows the for statement in action. Figure 7-17 shows the results of running this program.

Example 7.11: ForStatementTest.java

image from book
 1    public class ForStatementTest { 2      public static void main(String[] args){ 3 4         for(int i = 0; i < 10; i++){ 5           System.out.println("The value of i = " + i); 6         } 7      } 8    }
image from book

image from book
Figure 7-17: Results of Running Example 7.11

Referring to example 7.11 — the for statement begins on line 4. Notice how the integer variable i is declared and initialized in the first expression. The second expression compares the value of i to the integer literal value 10. The third expression increments i using the ++ operator.

In this example I have enclosed the single body statement in a code block (Remember, a code block is denoted by a set of braces.) However, if a for statement is only going to execute one statement you can omit the braces. (This goes for the while and do loops as well.) For example, the for statement shown in example 7.11 could be rewritten in the following manner:

                 for(int i = 0; i < 10; i++)                   System.out.println("The value of i = " + i );

Nesting Iteration Statements

Iteration statements can be nested to implement complex programming logic. For instance, you can use a nested for loop to calculate the following summation:

image from book

Example 7.12 offers one possible solution. Figure 7-18 shows the results of running this program using various inputs.

Example 7.12: NestedForLoop.java

image from book
 1    public class NestedForLoop { 2      public static void main(String[] args){ 3         int limit_i = Integer.parseInt(args[0]); 4         int limit_j = Integer.parseInt(args[1]); 5         int total = 0; 6 7         for(int i = 1; i <= limit_i; i++){ 8           for(int j = 1; j <= limit_j; j++){ 9              total += (i*j); 10          } 11        } 12        System.out.println("The total is: " + total); 13     } 14   }
image from book

image from book
Figure 7-18: Results of Running Example 7.12

Referring to example 7.12 — this program takes two strings as command-line arguments, converts them into integer values, and assigns them to the variables limit_i and limit_j. These variables are then used in the middle expression of each for loop to compare against the values of i and j respectively. Notice too that indenting is used to make it easier to distinguish between the outer and inner for statements.

Mixing Selection & Iteration Statements: A Powerful Combination

You can combine selection and iteration statements in practically any fashion to solve your particular programming problem. You can place selection statements inside the body of iteration statements or vice versa. Refer to the robot rat program developed in chapter 3 for an example of how to combine control-flow statements to form complex programming logic. Example 7.13 offers another example. The CheckBookBalancer class below implements a simple program that will help you balance your check book. It reads string input from the console and converts it into the appropriate form using the Double primitive-type wrapper class. It also uses try/catch blocks because there is a chance that reading input using the BufferedReader readLine() method may throw an IOException. Figure 7-19 shows an example of CheckBookBalancer in action.

Example 7.13: CheckBookBalancer.java

image from book
 1     import java.io.*; 2 3     public class CheckBookBalancer { 4        public static void main(String[] args){ 5          /**** Initialize Program Variables ******/ 6          InputStreamReader input_stream = new InputStreamReader(System.in); 7          BufferedReader console = new BufferedReader(input_stream); 8          char keep_going = 'Y'; 9          double balance = 0.0; 10         double deposits = 0.0; 11         double withdrawals = 0.0; 12         boolean good_double = false; 13 14         /**** Display Welcome Message ****/ 15         System.out.println("Welcome to Checkbook Balancer"); 16 17 18         /**** Get Starting Balance *****/ 19         do{ 20          try{ 21            System.out.print("Please enter the opening balance: "); 22            balance = Double.parseDouble(console.readLine()); 23            good_double = true; 24            }catch(Exception e){ System.out.println("Please enter a valid balance!");} 25           }while(!good_double); 26 27 28          /**** Add All Deposits ****/ 29          while((keep_going == 'y') || (keep_going == 'Y')){ 30              good_double = false; 31              do{ 32                try{ 33                   System.out.print("Enter a deposit amount: "); 34                   deposits += Double.parseDouble(console.readLine()); 35                   good_double = true; 36                   }catch(Exception e){ System.out.println("Please enter a valid deposit value!");} 37                 }while(!good_double); 38                System.out.println("Do you have to enter another deposit? y/n"); 39                try{ 40                  keep_going = console.readLine().charAt(0); 41                   }catch(Exception e){ System.out.println("Problem reading input!");} 42          } 43 44          /**** Subtract All Checks Written ****/ 45           keep_going = 'y'; 46           while((keep_going == 'y') || (keep_going == 'Y')){ 47               good_double = false; 48               do{ 49                 try{ 50                    System.out.print("Enter a check amount: "); 51                    withdrawals += Double.parseDouble(console.readLine()); 52                    good_double = true; 53                    }catch(Exception e){ System.out.println("Please enter a valid check amount!");} 54                  }while(!good_double); 55                System.out.println("Do you have to enter another check? y/n"); 56                try{ 57                  keep_going = console.readLine().charAt(0); 58                   }catch(Exception e){ System.out.println("Problem reading input!");} 59           } 60 61           /**** Display Final Tally ****/ 62 63           System.out.println("***************************************"); 64           System.out.println("Opening balance:      $  " + balance); 65           System.out.println("Total deposits:      +$  " + deposits); 66           System.out.println("Total withdrawals:   -$  " + withdrawals); 67           balance = balance + (deposits - withdrawals); 68           System.out.println("New balance is:       $  " + balance); 69           System.out.println("\n\n"); 70     } 71    }
image from book

image from book
Figure 7-19: Results of Running CheckBookBalancer

Quick Review

Iteration statements repeat blocks of program code based on the result of a conditional expression evaluation. There are three types of iteration statements: while, do/while, and for. The while statement evaluates its conditional expression before executing its code block. The do/while statement executes its code block first and then evaluates the conditional expression. The for statement provides a convenient way to write a while statement as it combines loop variable counter declaration and initialization, conditional expression evaluation, and loop counter variable incrementing in a compact format.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net