Using the switch Statement Programmers commonly find themselves in situations where they need to test the value of an expression against some set of values.. If you don’t use the break s
Trang 1Nesting if-else Structures
So far, you are able to conditionally execute one of two statements based on a sin-gle condition Sometimes you need to have more than two branches in the flow
of your program based on a set of related conditions This is possible in Java You know that in the if-elsestructure, the statement (any valid Java statement) that the program executes if the condition is false follows the elsekeyword The key
here is any valid Java statement—including another conditional statement These types of structures are called nested if-else statements Take a look at the syntax:
if (condition1) {
java_statements_for_true_condition1;
}
else if (condition2) {
java_statements_for_true_condition2;
} else {
java_statements_for_false_conditions;
}
If condition1is true, the program executes java_statements_for_true_condi-tion1 If condition1is false, condition2is tested You do this by immediately fol-lowing the elsekeyword with another ifconditional statement If condition2is true, the program executes java_statements_for_true_condition2 Finally, if neither condition is true the java_statements_for_false_conditions are exe-cuted Take a look at this quick example, and then move on to the next section where you use apply this concept in an actual program:
if (name == “Joseph”) { System.out.println(name + “ is my first name.”);
} else if (name == “Russell”) { System.out.println(name + “ is my last name.”);
} else { System.out.println(name + “ is not my name.”);
}
78
J a
s o
l ut
n e
FIGURE 3.10
This is several runs of the HighOrLowTemp program.
Trang 2Assume that nameis a string holding some person’s name This snippet of code indicates that the name is my first name if it is “Joseph“, else if it is “Russell“, the code indicates that it is my last name If it is neither my first name nor my last name, the code indicates that it is not my name
The ManyTemps Program
The ManyTempsprogram demonstrates the use of the nested if-elsestructure It prints a different message depending on the range of the randomly generated temperature
/*
* ManyTemps
* Demonstrates if-else nesting structure.
*/
import java.util.Random;
public class ManyTemps { public static void main(String args[]) { int min = -40;
int max = 120;
int diff = max - min;
int temp;
Random rand = new Random();
temp = rand.nextInt(diff + 1) + min;
System.out.println(“The temperature is “ + temp +”F.”);
if (temp < -20) { System.out.println(“It’s DANGEROUSLY FREEZING! Stay home.”);
} else if (temp < 0) { System.out.println(“It’s extremely cold! Bundle up tight.”);
} else if (temp < 33) { System.out.println(“It’s cold enough to snow.”);
} else if (temp < 50) { System.out.println(“You should bring a coat.”);
} else if (temp < 70) { System.out.println(“It’s nice and brisk.”);
} else if (temp < 90) { System.out.println(“It’s warm outside.”);
} else if (temp < 100) { System.out.println(“It’s hot Stay in the shade.”);
}
79
Trang 3else { System.out.println(“I hope you have an air conditioner!”);
} } } There are a couple of things to explain here One thing is that you can nest as many if-elsestatements as you need to Another thing worth mentioning is with the way that these ifconditions are nested here, you can assume the value
of the conditions that are evaluated in previous ifconditions within the same nested structure The first condition temp < –20 assumes nothing about temp
except that it can be less than –20 The next condition temp < 0assumes that the temperature is not less than –20because if it were, the program would never get
to this point So if the condition temp < 0evaluates to true, the program right-fully assumes the temperature ranges somewhere between –20 and –1 This is why, although tempis random, the final elsestatement can assume that the tem-perature is not less than 100and can safely mention the air conditioner Figure 3.11 displays the output of several runs of this program
80
J a
s o
l ut
n e
Indentation and Syntax Conventions
As you can see in all the examples using the ifstatement, for the sake of read-ability, I tend to use the following spacing and syntax conventions for if-else
structures Other people might have their own style I follow the ifkeyword with
a space, and then I type the condition within the parentheses Within the con-dition, I use spaces between operands and operators I also tend to use parenthe-ses, even when technically not necessary, within the conditional expression if the evaluation order could possibly be confusing later
After the condition, I use a space and then open the brace for the block statement that executes if the condition is true As you read later chapters, you notice that
FIGURE 3.11
The ManyTemps program conditionally prints one of eight messages.
Trang 4I don’t always use braces If there is only one simple statement that follows the condition, I tend to omit the brace; however, in nested if-elsestatements, or any other ifstatements that might be confusing, I use them I indent lines within the braces two or three spaces, so they will be quickly identifiable as being part
of the block statement I always close braces on lines of their own and use the same indentation I used with the line with the opening brace
You can develop your own style of spacing and indentation, but keep in mind that in the real world, your company might have its own conventions that it requires all of its programmers to follow In any case, keeping all of its code con-sistently formatted makes it so much more readable when working with other programmers’ code
Using the switch Statement
Programmers commonly find themselves in situations where they need to test the value of an expression against some set of values If the expression is not equal to the first value, test it against the second value If the expression is not equal to the second value, test it against the third one, and so on You can accom-plish this with an if-elsestructure, but there is an alternative, neater, way to do
it Consider printing a text description of a number, n, that can range from one through five Using the if-elsestructure, you do it this way:
if (n == 1) { System.out.println(“one”);
} else if (n == 2) { System.out.println(“two”);
} else if (n == 3) { System.out.println(“three”);
} else if (n == 4) { System.out.println(“four”);
} else if (n == 5) { System.out.println(“five”);
} else { System.out.println(“some other number”);
} You can see how many times I needed to repeat the nvariable You can probably also imagine how confusing this structure would be if I were testing for even more different values or if nwasn’t just a variable, but a complex expression that would need to be repeated in each condition Take a look at how I write this using the switchstatement:
81
Trang 5switch (n) { case 1:
System.out.println(“one”);
break;
case 2:
System.out.println(“two”);
break;
case 3:
System.out.println(“three”);
break;
case 4:
System.out.println(“four”);
break;
case 5:
System.out.println(“five”);
break;
default:
System.out.prinln(“some other number”);
} You can immediately see that I only have to reference the nvariable once in this switch block The syntax for the switchconditional statement is as follows:
switch (expression) { case value1:
statements_for_value1;
break;
case value2:
statements_for_value2;
break;
case value3:
statements_for_value3;
break;
default:
statements_for_any_other_value;
} The switch keyword is followed by an expression in parentheses The type of this expression must evaluate to char, byte, short, or int If it doesn’t, you get a compile-time error After the expression, you open the block using the brace Fol-lowing that is the casekeyword, and then the value to compare the expression
to and a colon After the colon, place any statements to be executed if the expres-sion is equal to the value that follows this particular case After that, you use the
break keyword to exit the switch statement The default keyword, which is optional, is used to define statements that execute if the expression doesn’t equal any of the casevalues
The switch block is useful if you need to perform one action for multiple values Take the following switch block that prints a message for multiples of 10 as an example:
T R I C K
82
J a
s o
l ut
n e
Trang 6switch (n) { case 1:
case 2:
case 5:
case 10:
System.out.println(n + “ is a multiple of 10.”);
break;
default:
System.out.println(n + “ is not a multiple of 10.”);
}
The cases in which n is a multiple of 10 do not have any statements in them (although they can), most importantly though, they don’t use the break statement.
This allows the appropriate message to print for values 1 , 2 , 5 , or 10
83
W AR S TORY
When switch statements were fairly new to me I kept forgetting to use the break
statements and I was getting some weird results If you don’t use the break
statements where you need to, the flow of the switch block moves into the next
case statement and executes whatever other statements it finds there I was baffled by what was going on I was working with random numbers, but my results weren’t random Of course, I automatically assumed that there was some problem with the way my code was generating random numbers I wasted a lot of time before I finally realized what my mistake was If you get into the habit of always using if structures and hardly ever using switch , like I once did, try not to forget about the break statements when you actually do use
a switch block.
The FuzzyDice Program
This program uses the switchconditional structure to print the face value of one die The face value of the die is generated randomly and the program tests it for values being equal to one of the face values of a six-sided die: 1through 6 Here
is the source code listing for FuzzyDice.java: /*
* FuzzyDice
* Demonstrates use of the switch structure
*/
import java.util.Random;
public class FuzzyDice {
Trang 7public static void main(String args[]) { Random random = new Random();
int die;
String s;
System.out.println(“Rolling die ”);
die = random.nextInt(6) + 1;
s = “\n -”;
switch (die) { case 1:
s = s + “\n| |”;
s = s + “\n| * |”;
s = s + “\n| |”;
break;
case 2:
s = s + “\n| * |”;
s = s + “\n| |”;
s = s + “\n| * |”;
break;
case 3:
s = s + “\n| * |”;
s = s + “\n| * |”;
s = s + “\n| * |”;
break;
case 4:
s = s + “\n| * * |”;
s = s + “\n| |”;
s = s + “\n| * * |”;
break;
case 5:
s = s + “\n| * * |”;
s = s + “\n| * |”;
s = s + “\n| * * |”;
break;
case 6:
s = s + “\n| * * |”;
s = s + “\n| * * |”;
s = s + “\n| * * |”;
break;
default:
//should never get here
s = s + “\n| |”;
s = s + “\n| |”;
s = s + “\n| |”;
}
s = s + “\n -”;
System.out.println(s);
} }
84
J a
s o
l ut
n e
Trang 8dieis a random integer ranging inclusively from 1through 6 The switchblock uses the dievariable as its expression The program tests the value and condi-tionally builds a string that represents a “drawing” of the face of the die based
on its value If the program generates the random number correctly, it will never reach the defaultstatements that build a string that represents a blank die face
Figure 3.12 demonstrates a couple of runs of this program
85
Understanding Arrays
An array is a list of primitive data type values or objects It is a way to store
col-lections of items of the same data type under one variable name Arrays are actu-ally objects themselves and can be treated as such You’ve already worked with arrays somewhat in Chapter 2 when you learned about accepting command-line arguments Recall that the single parameter accepted by an application’s main()
method is an array of strings Now you learn about arrays in more detail To cre-ate an array, you need to declare it, assign it an array object, and then you can assign actual values within the array
Declaring an Array
When declaring an array, you need to specify the data type that the array will maintain in its list You need to give it a variable name and specify it as being an array by using square brackets ([]) Here are a few examples of declaring arrays:
int sillyNumbers[];
double mealPrices[];
Object objectList[];
boolean testAnswers[];
You can use the brackets where they are used previously, or you can optionally use the brackets after the data type When I declare arrays, I do it this way:
FIGURE 3.12
The FuzzyDice program randomly creates pictures of the face of a die.
Trang 9int[] sillyNumbers;
double[] mealPrices;
Object[] objectList;
boolean[] testAnswers;
After you declare an array variable, you need to assign an array object to it before you can start using it You do this by using the newkeyword like you do when
cre-ating any new object You have to specify the array length, which is its size, or
more specifically, the number of items it can hold—its capacity You define the length of an array within the square brackets of the array object you are creating The following examples assign array objects to the arrays declared previously: sillyNumbers = new int[10];
mealPrices = new double[18];
objectList = new Object[3];
testAnswers = new boolean[100];
After these array objects are created, sillyNumbersis an array able to hold 10 integers, mealPricesis an array able to hold 18 doubles, objectListis an array able to hold 3 objects, and testAnswersis an array able to hold 100 Booleans
Assigning Values to and Accessing Array Elements
After you declare an array and assign an array object to it, you can assign values
to the array elements Array elements are the individual values stored under spe-cific subscripts of the array Array subscripts are integers that represent an item’s
position within the array An array subscript is also called an array index The element’s subscript is specified within square brackets that follow the array’s name Here are some examples to clear things up:
sillyNumbers[0] = 3000;
sillyNumbers[9] = 1;
The first line assigns 3000to the first element of the sillyNumbersarray The first element of an array is always indexed by 0 The second line assigns the integer 1
to the array’s last element Note that the subscript of the last element of an array
is equal to one less than the array’s total length because the subscripts start at 0, not 1
You can also declare an array, assign an array object, and assign values to the array’s elements on one line The following line declares an array of strings,
family Using braces and specifying the elements’ values, in order, separated by commas initializes the elements of the array The length of familyis 5because it
is initialized using 5strings:
String[] family = {“Vito”, “Santino”, “Michael”, “Fredo”, “Connie”};
86
J a
s o
l ut
n e
Trang 10After initializing this array, family[0]is “Vito”, family[1]is “Santino”, and so
on Let’s get rid of “Fredo”because he sleeps with the fishes:
family[3] = null;
Okay, that’s taken care of You can access elements that are already stored in the array by using its subscript, just like when you assign its value When you access
an array element, you can treat it like any other variable of the same type For example:
System.out.println(“Don “ + family[0] + “ Corleone”);
This line prints “Don Vito Corleone” You can get the length of an array by using the syntax: arrayName.length Remember that the last subscript of an array is one less than its length If you attempt to access an element of an array by using a subscript that is out of the array’s bounds (by using a number that is not a subscript of the array, usually greater than the last subscript), you get a run-time error, as shown in Figure 3.13
The ArrayOOB program demonstrates this The source code listing for Array-OOB.javais listed here:
/*
* ArrayOOB
* Demonstrates what happens when an array index
* is out of bounds.
*/
public class ArrayOOB { public static void main(String args[]) { //declare an array of length 10 int[] arr = new int[10];
//incorrect attempt to access its last value System.out.println(“Last value: “ + arr[10]);
87
FIGURE 3.13
This program causes an ArrayIndexOutOf BoundsException and crashes.