Java Reference
In-Depth Information
public static void main(String[] args) {
int nHats = 1; // Number of hats
System.out.println("I have " + nHats + " hat" + (nHats == 1 ? "." : "s."));
nHats++; // Increment number of hats
System.out.println("I have " + nHats + " hat" + (nHats == 1 ? "." : "s."));
}
}
The output from this program will be:
I have 1 hat.
I have 2 hats.
How It Works
The result of the conditional operator is a string containing just a period when the value of nHats is 1,
and a string containing an s followed by a period in all other cases. The effect of this is to cause the
output statement to automatically adjust the output between singular and plural. You can use the same
technique in other situations such as where you need to choose "he" or "she" for example, as long as
you are able to specify a logical expression to differentiate the situation where you should use one rather
than the other.
The switch Statement
The switch statement enables you to select from multiple choices based on a set of fixed values for a
given expression. The expression must produce a result of type char , byte , short or int , but not
long , otherwise the statement will not compile. In normal use it operates rather like a rotary switch in
that you can select one of a fixed number of choices. For example, on some makes of washing machine
you choose between the various possible machine settings in this way, with positions for cotton, wool,
synthetic fiber and so on, which you select by turning the knob to point to the option that you want.
A switch statement reflecting this logic would be:
switch(wash) {
case 1: // wash is 1 for Cotton
System.out.println("Cotton selected");
break;
case 2: // wash is 2 for Linen
System.out.println("Linen selected");
break;
case 3: // wash is 3 for Wool
System.out.println("Wool selected");
break;
default: // Not a valid value for wash
System.out.println("Selection error");
break;
}
Search WWH ::




Custom Search