THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Exercise 10.1: Using ifelse in a loop, write a method that takes a string parameter and returns a string with
all the special characters in the original string replaced by their language equivalents. For example, a string
with a " in the middle of it should create a return value with that " replaced by \". (Section 7.2.3 on page 167
lists all special characters).


10.3. switch


A switch statement allows you to transfer control to a labeled entry point in a block of statements, based on
the value of an expression. The general form of a switch statement is:


switch (expression) {
case n: statements
case m: statements


...
default: statements
}


The expression must either be of an integer type (char, byte, short, or int, or a corresponding wrapper
class) or an enum type. The body of the switch statement, known as the switch block, contains statements
that can be prefixed with case labels. A case label is an integer or enum constant. If the value of the
switch expression matches the value of a case label then control is transferred to the first statement
following that label. If a matching case label is not found, control is transferred to the first statement
following a default label. If there is no default label, the entire switch statement is skipped.


For example, consider our Verbose interface from page 121:


interface Verbose {
int SILENT = 0;
int TERSE = 1;
int NORMAL = 2;
int VERBOSE = 3;


void setVerbosity(int level);
int getVerbosity();
}


Depending on the verbosity level, the state of the object is dumped, adding new output at greater verbosity
levels and then printing the output of the next lower level of verbosity:


Verbose v = ... ; // initialized as appropriate
public void dumpState() {
int verbosity = v.getVerbosity();
switch (verbosity) {
case Verbose.SILENT:
break; // do nothing


case Verbose.VERBOSE:
System.out.println(stateDetails);
// FALLTHROUGH


case Verbose.NORMAL:
System.out.println(basicState);
// FALLTHROUGH

Free download pdf