Version 5.11
Two class days
Handouts: WeirdLoops.java
switch statementEvaluates one expression and compares it to different values; executes statements corresponding to the first value that the expression equals.
break statementdefault caseSketch of syntax (simplified):
switch (expr) {
case value1:
statement;
...
break;
case value2:
statement;
...
break;
default:
statement;
...
[break;]
}
expr and values must be either int or char in type—not boolean, not any floating point type, and not any other integer type—of course, also not any reference type.break; is optional, but why is it a good idea?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.
break statements?default case?break statement at the end of the default case?An if-like expression:
condition ? valueIfTrue : valueIfFalse
Can be used to abbreviate alternate assignments to the same variable, or as an argument in a method call (pp. 274–275)
do statementLike 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);
do Statementdouble x = 12.0;
do {
System.out.println(x);
x /= 2.0;
}
while (x > 3.5)
What if x is initialized as 3.1?
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.
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.
Uses a for loop to print out the multiples of a number up to a user-specified limit. The update is mult += value;
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.
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
for and while iterate 0 or more times; do iterates at least 1 time.
for and while evaluate test at the start; do evaluates test at the end.
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").
if, while, and for statements
do while, switch, and conditional operator
; (empty statement) as loop bodyfor loops without init, test, update
true, i.e., loop foreverVariations 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.
while statement.do while statement.for statement.if statement to check that n ≥ 0?Loops and conditionals can result in some interesting graphical programs.
for loop draws concentric circles with decreasing radius; the conditional selects the color. The result is a series of rings alternating black and white.
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)!
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:
static String showInputDialog(Object msg) — uses msg to request user input into a text input field and returns the input as a String;
static int showConfirmDialog (Component parent, Object msg) — provides Yes, No, and Cancel buttons; returns int values such as JOptionPane.YES_OPTION.
static void showMessageDialog (Component parent, Object msg) — displays a message and an OK button to close the dialog box.
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.
Demonstrates the three types of dialog box.
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." ↩