Chapter 6: More Conditionals and Loops

Version 5.11

Two class days

Handouts: WeirdLoops.java

First Day

(6.1) The switch statement

Evaluates one expression and compares it to different values; executes statements corresponding to the first value that the expression equals.

Sketch of syntax (simplified):

switch (expr) {
  case value1:
    statement;
    ...
    break;
  case value2:
    statement;
    ...
    break;
  default:
    statement;
    ...
    [break;]
}

Example

int x = ...;
... 
switch (x + 2) { 
  case 4: 
    System.out.println("x is 2"); 
    break; 
  case 5: 
    System.out.println("x is 3"); 
    break; 
  default: 
    System.out.println("x is neither 2 nor 3"); 
    break; // optional 
}

Paraphrased as an 'if' statement:

int x = ...;
... 
if (x + 2 == 4) 
  System.out.println("x is 2"); 
else if (x + 2 == 5) 
  System.out.println("x is 3"); 
else 
  System.out.println("x is neither 2 nor 3");

A switch statement can always be paraphrased using if ... else if ...; but it is sometimes more convenient.

However, nested ifs are really not that difficult to comprehend, contra p. 273.

The if statement is more general than switch, because it can use (a) comparisons other than equality, and (b) types other than char and int.

Listing 6.1 GradeReport

(6.2) The Conditional Operator

(6.3) The do statement

Like the while statement, but with the test for expr occuring at the end rather than at the beginning. Always executes its statement at least once.

Syntax:

do
  statement
while (expr);

Example of do Statement

double x = 12.0;
do {
  System.out.println(x);
  x /= 2.0;
}
while (x > 3.5)

What if x is initialized as 3.1?

Listing 6.2 ReverseNumber

Uses a do statement to print out the decimal digits of an integer, in reverse order. Uses % and / to extract the digits.

Trace the execution with at least one example.

(6.4) The for Statement

Another iteration control statement, especially good when we can tell the number of iterations at the outset.

Example:

for (int i = 0; i < 10; i++)
  System.out.println(i);

Equivalent to:

{
  int i = 0;
  while (i < 10)
  {
    System.out.println(i);
    i++;
  }
}

Syntax:

for (init; test; update)
  statement

Semantics: equivalent to

{
  init;
  while (test) 
  {
    statement;
    update;
  }
}

Simple usage with ++ or -- in the update:

count++ // p. 279
num--   // p. 280

The init may contain a variable declaration.

The update can perform any kind of update; normally, it changes the variable initialized in the init.

Listing 6.3 Multiples

Uses a for loop to print out the multiples of a number up to a user-specified limit. The update is mult += value;

Listing 6.4 Stars

Uses nested for loops. The outer loop prints one line per iteration. The inner loop prints one * per iteration. Each line is one * longer than the previous.

Iterators and for loops

New syntax in Java 1.5 (5): enhanced for statement (for-each loop): given a collection with an iterator,

for (type elt : iterator)
  statement;

Equivalent to:

while (iterator.hasNext()) {
  elt = iterator.next();
  statement;
}

This also works for Iterables as well as Iterators. An Iterable object is one one that has an iterator, which can be got by calling the object's iterator() method. Lists and other collections are usually Iterables.2

for (type elt : collection)
  statement;

Equivalent to:

Iterator iterator = collection.iterator(); // gets the iterator while
(iterator.hasNext()) { elt = iterator.next(); statement; }

Example: foreach.java

Comparing loops

  1. for and while iterate 0 or more times; do iterates at least 1 time.

  2. for and while evaluate test at the start; do evaluates test at the end.

  3. while and do allow indefinite iteration (where the number of iterations cannot be determined in advance).

    Actually, so does for, but it is especially well suited for for definite iteration (where the number of iterations is knowable in advance), such as counting loops ("repeat 10 times").

Key Points

Loop Bugs and Tricks

Second Day

Exercises

Variations on Exercise 6.12 (p. 295):

Write and test a method that prints the powers of 2 from 20 = 1 to 210 = 1024. The method has no parameters and returns no value.

Introduction to Lab 5

(6.5) Drawing with loops and conditionals

Loops and conditionals can result in some interesting graphical programs.

Listings 6.5–6.6: Bullseye, BullseyePanel

for loop draws concentric circles with decreasing radius; the conditional selects the color. The result is a series of rings alternating black and white.

Listings 6.7–6.8: Boxes, BoxesPanel

Uses a loop to draw a collection of random boxes; their color and fill properties are conditionally determined from the box's height and width.

Interesting — the paintComponent method generates a new collection of boxes each time it runs, so if you hide and reshow the window, you get a new picture (and if you hide and reshow a part of it, it looks strange)!

(6.6) Dialog boxes

Dialog boxes are pop-up windows that engage the user briefly, e.g., to choose a file, to confirm a command, or simply to read a message.

The class javax.swing.JOptionPane has useful methods for creating dialog boxes:

The parent argument represents the component over which the dialog box appears; if it is null, the dialog box is placed in the center of the screen.

Listing 6.9 EvenOdd

Demonstrates the three types of dialog box.


  1. Version log:
    • Version 5.1, 2012 Feb 14. Linked in for-each example.
    • Version 5.0, 2012 Feb 2–11. Split chapter 5 into chapters 5 and 6.
    • Version 4.1, 2011 Feb 11. Converted to markdown.
    • Version 4, 2010 Feb 5. Converted to RST.
    • Version 3, 2009 Feb 16. Added new examples.
    • Version 2, 2009 Feb 10. Updated for 6th edition.
  2. Iterable (java.lang.Iterable) is an interface; which declares the iterator() method returning an Iterator (java.util.Iterator). The purpose of the Iterable interface seems to be, as the API documentation describes it, "Implementing this interface allows an object to be the target of the 'foreach' statement."