i o The CountByFive Program The CountByFive program shown in Figure 4.4 uses the compound increment assignment operator to increment the ivariable by five after each iteration of the loo
Trang 1Skipping Values
In the previous section, you learned about the increment operator ++ As you know, this operator causes the operand to be incremented by one What if you wanted to skip values while incrementing your variable in the loop? You can write a loop that counts in increments of five like this:
for (int i=5; i<=100; i = i + 5) { System.out.print(i + “, “);
} The output of this program is 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55,
60, 65, 70, 75, 80, 85, 90, 95, 100 There is a niftier way to do this, described
in the next section
public static void main(String args[]) { int x = 0, y = 0, a = 0, b = 0;
System.out.println(“y and x both = 0”);
y = x++;
System.out.println(“The expression y = x++ “
+ “results in y = “ + y + “ and x = “ + x);
System.out.println(“a and b both = 0”);
b = ++a;
System.out.println(“The expression b = ++a “
+ “results in b = “ + b + “ and a = “ + a);
} } The output of this program is displayed in Figure 4.3 Note that the variable yis assigned the value 0, which is the value of xbefore it is incremented because that
is the value of the postfix increment expression On the other hand, the value of the bvariable is 1, which is the value of aafter it is incremented Although this type of distinction might seem trivial to you at the moment, it is an important concept for you to understand
98
J a
s o
l ut
n e
FIGURE 4.3
The PrePost
application demonstrates the difference between prefix and postfix increment operations.
Trang 2i o
The CountByFive Program
The CountByFive program (shown in Figure 4.4) uses the compound increment assignment operator to increment the ivariable by five after each iteration of the loop A compound assignment operator combines an arithmetic operation and
an assignment in one operator Take a look at the source code and the output:
/*
* CountByFive
* Demonstrates skipping values when incrementing numbers
* in a loop using the += operator
*/
public class CountByFive { public static void main(String args[]) { for (int i=5; i <= 100; i+=5) { System.out.print(i);
if (i < 100) System.out.print(“, “);
} } }
I N THE R EAL W ORLD
In the real world, skipping values is useful You might have an array that stores sets of data For example, you can write an array that stores item numbers and inventory counts, called inventory[] In this array, inventory[0] stores the first item number and inventory[1] stores the quantity of that item in your inventory.
Following this pattern, all even indices store item numbers and any given odd index stores the quantity of the item that precedes it in the array If you wanted
to initialize your inventory to zero, you would only want to affect the odd num-bers (to set the quantities all to zero).
FIGURE 4.4
The CountByFive
program counts to one hundred in increments of five.
Trang 3Using Compound Assignment Operators
The +=operator used in the CountByFiveprogram is one of the compound assign-ment operators You can see some others in Table 4.1 As described earlier, com-pound assignment operations combine an arithmetic operation with an assignment operation The syntax for compound assignment operations is:
variable op= expression;
Where variableis a variable of some primitive type, opis a mathematical oper-ator, and expressionis an expression that evaluates to some value that can be cast to the primitive type of the variable Consider the example:
int x = 1;
x += 5;
The result of xbecomes 6 It is initialized to 1, and then 5is added to it Also con-sider this less intuitive example:
int x = 1;
x += 5.9;
The result of x at the end of this operation is still 6 Performing a compound assignment operation implies a cast of the right-side expression to the data type
of the variable In this example, 5.9is cast (converted to) the integer 5before it is added to x I mentioned that the variable must be of some primitive type There
is an exception to this rule, but only specifically for the +=operator The variable might also be a string When the left operand is a string, the right-side operand can be of any type The following example uses the increment assignment oper-ator on a Stringvariable
String s = ““;
s += 1;
s += “, “;
s += 2;
s += ‘,’;
s += “ buckle my shoe”;
The value of sbecomes “1, 2, buckle my shoe” Here the code initializes sto the empty String ““, and then each subsequent operation appends the right-side operand to s
There are also compound assignment operators: &= , |= , and ^= in Java for Boolean logical operations, as well as <<= , >>= , and <<<= for bit shift operations These operations are out of the scope of this book For more information about them, follow this URL: http://java.sun.com/docs/ books/jls/second_edition/html/j.title.doc.html.
H I N T
100
J a
s o
l ut
n e
Trang 4Counting Backwards
So far, every forloop you’ve encountered counts forwards, but you can also write
a forloop in such a way that it counts backwards You might want to do this in your Java programs in order to perform quicker array searches For example, if you had an array of Stringobjects sorted alphabetically and you needed to loop through your array to see whether the word “zebra” was stored there, you would probably want to start searching from the last entry and work your way back-wards since that word would be toward the end of the array It would take longer, especially if you had a huge array, to start from the beginning and loop through
to the end You initialize the variable used to keep track of the loop’s iterations
to some higher value than the sentinel value, and then decrement it after each
iteration through the loop until the sentinel value is reached A sentinel, much
like the squid-like sentinel killing machines from The Matrix, is used to kill It
kills a loop (stops it from repeating) Actually, the term sentinel is better used to describe a situation in which you are looking for some exact value (the sentinel value) before exiting the loop, but some programmers prefer to use it more loosely to mean whatever condition causes the loop to terminate The CountDown
program (shown in Figure 4.5) uses a forloop to count backwards:
/*
* CountDown
* Demonstrates how to make a for loop count backwards
* by using the operator
*/
public class CountDown {
public static void main(String args[]) { System.out.println(“Countdown:”);
System.out.print(“T-”);
101
i o
*= Multiplication assignment operator x *= 5; x = x * 5;
T A B L E 4 1 C O M P O U N D A S S I G N M E N T O P E R A T O R S
Trang 5for (int t=10; t > 0; t ) { System.out.print(t + “ “);
} System.out.println(“\nBLASTOFF!”);
}
}
102
J a
s o
l ut
n e
FIGURE 4.5
The CountDown
program uses a
for loop to count backwards.
Making a for Loop Count Backwards
In the CountDownprogram, you wrote a forloop that counts backwards from 10
In order to accomplish this, you initialize the tvariable to the value 10 Remem-ber that in a forloop, the initial value of the loop variable is the value it contains during the first iteration of the loop, which is why the first time tis printed, its value is 10 You want this loop to terminate when treaches zero, so you use the condition t > 0 Although tis greater than zero, this loop will continue to iter-ate Each time through the loop you decrement tby one You do this by using the
decrement operator––- This operator works very similarly to the increment oper-ator you learned about earlier except that it subtracts one from the operand instead of adding one
//These three lines of code do the same thing – subtract one from x
x = x - 1;
x ;
x;
The same prefix and postfix rules apply to the decrement operator If the prefix decrement operator is used in an assignment (such as y = ––x;), y will be assigned the value of xbefore it is decremented by one If the postfix operator is used (such as y = x––;), ywill be assigned the value of xafter it is decremented
by one
Trang 6Nested for Loops
You can put any valid Java code within a forloop That includes another loop If
you place one loop inside another loop, the inner loop is called a nested loop For
each iteration of the outer loop, the inner loop is executed as well The flow of the code works as follows The interpreter enters the outer forloop The code for the outer loop initializes a variable and enters the body of the loop if the value
of the condition is true Then within the body of the outer loop, another loop exists The interpreter enters that loop, which initializes its own variable and the code enters the body of this loop if its condition is true This inner loop will con-tinue to iterate until its condition evaluates to false Then, ultimately, the con-trol will return to the outer loop, which will continuously cause subsequent calls
to the inner loop until its own condition evaluates to false You use nested loops
to iterate through multidimensional arrays Confused? This next example will help
/*
* NestedLoops
* Demonstrates the use of nested for loops
*/
public class NestedLoops {
public static void main(String args[]) { for (int i=0; i < 3; i++) {
for (int j=0; j < 3; j++) { System.out.println(“[i][j] = [“ + i + “][“ + j + “]”);
} } }
} The NestedLoopsprogram, as described most basically, counts to 3 three times
The loop’s variables, i for the outer loop and j for the inner loop, are incre-mented after each iteration of their respective loops As you can see in the out-put of this program in Figure 4.6, the ivariable in the outer loop is initialized to zero Then the inner loop’s jvariable is initialized to zero This fact is illustrated
in the first line of output Then, jis incremented by one, so j= 1 Because the condition of the inner loop, j < 3is still true, the body of the inner loop is exe-cuted again The second line of output shows that iis still zero and jis now one
The inner loop continues to iterate until j is no longer less than three At this point, control is returned to the outer loop iis incremented by one, and because
i is still less than three, the inner loop is entered once again The j variable is again initialized to zero and the inner loop iterates again until jis not less than three Then iis incremented again And the list goes on
103
i o
Trang 7Another example of nesting loops is the MultiplicationTableprogram It uses nested forloops to print the multiplication table you might remember from the inside cover of your elementary school math book or notebook Here is a listing
of MultiplicationTable.java: /*
* MultiplicationTable
* Prints the multiplication table using nested loops
*/
public class MultiplicationTable {
public static void main(String args[]) { for (int i=1; i <=12; i++) {
System.out.print(‘\n’);
for (int j=1; j <= 12; j++) { System.out.print((i * j + “ “).substring(0, 5));
} } }
} The ivariable of the outer loop counts from 1to 12and so does the jvariable of the inner loop Inside the outer loop, before getting to the inner loop, it prints a new line character \n The inner loop prints all the output on a single line, so that is why the new line is printed right before it The line that produces the out-put in the inner loop, as follows,
System.out.print((I * j + “ “).substring(0, 5));
first takes i * jand appends four spaces to it (i * j + “ “),which creates
a string As you learned in Chapter 2, “Variables, Data Types, and Simple I/O,” the Stringmethod called substring()returns a piece of a string starting with the first index argument up to the string index that is one less than the second argument
104
J a
s o
l ut
n e
FIGURE 4.6
The NestedLoops
program demonstrates nesting loops.
Trang 8In this program, the first argument is 0and the second argument is 5 The rea-son you append spaces and then take a substring of the result is so that all the columns line up Doing it this way ensures that every time data is printed, it is the same string length The output is shown in Figure 4.7
105
i o
Looping on Arrays
As you know, arrays store their multiple elements by indexing them by integer subscripts To get all the values inside an array individually, you have to reference them all by the integer subscript For instance, if you want to print all the ele-ments of a small array, you can do it like this:
char[] myArray = { ‘a’, ‘b’, ‘c’};
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
FIGURE 4.7
The
Multiplication-Table program prints the multiplication table.
I N THE R EAL W ORLD
In the real world, just about all programs loop on some data, especially data-base applications A program might read in some data source, a file perhaps, and then temporarily store that data in an array Then the program will loop on that data, either searching for a particular entry to modify, or to modify all them
in some way Writing the data back to the file might occur in a separate loop.
Another program might be written to create a report on this data It will loop on
it to read it in and possibly loop on it again to resort the temporary structure to suit the particular report’s sorting preferences It might filter out some records, add up subtotals and grand totals, all in the same loop before printing the actual output Typically, a programmer is working with a great deal of data, and loops perform operations on it all.
Trang 9What if you had a huge array, though? You wouldn’t want to do it this way You can stick the array inside a loop that does all this work for you The previous action would better be implemented in a forloop like so:
char[] myArray = { ‘a’, ‘b’, ‘c’ };
for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i]);
}
Looping on Multidimensional Arrays
So far in this chapter, you have learned how to nest forloops and how to use for
loops to loop on arrays You just need to put these two concepts together to understand how to loop on multidimensional arrays Take a two-dimensional array for example Assume my2Darrayis a two-dimensional array that is already initialized This is how you loop on its contents:
for (int i = 0; i < my2Darray.length; i++) { for (int j = 0; j < my2Darray[i].length; j++) { System.out.println(my2Darray[i][j]);
} }
A multidimensional array is an array of arrays In the inner loop, where you check for the array length for the condition, you check the length of the array by referencing it this way: my2Darray[i].length This refers to the length of the array contained within my2Darrayat index i
Got more than a two-dimensional array? No problem Just nest another forloop There is a one to one ratio of nested forloops and dimensions of the array Here
is an example of how to loop on a three-dimensional array:
for (int i = 0; i < my3Darray.length; i++) { for (int j = 0; j < my3Darray[i].length; j++) { for (int k = 0; k < my3Darray[i][j].length; k++) { System.out.println(my3Darray[i][j][k]);
} } }
The MultiplicationArray Program
The MultiplicationArray program declares a multidimensional array of ints, called mTable.Its dimensions are twelve by twelve (twelve arrays, each of length twelve) First, the program generates the contents of the array within a nested for
loop This loop is a bit different than the previous examples The loops don’t start with their variables equal to zero; they start at one because the program builds the multiplication table based on integers one through twelve and doesn’t include zero As a result, the subscripts have to be referenced by subtracting one:
106
J a
s o
l ut
n e
Trang 10for (int i=1; i <=12; i++) { for (int j=1; j <= 12; j++) { mTable[i - 1][j - 1] = i * j;
} }
So mTable[0][0]is 1 * 1, mTable[1][1]is 2 * 2, mTable[4][6]is 4 * 7, and so
on After the program builds the array, it prints it similarly to the way that the
MultiplicationTableprogram did As you can see in the output shown in Figure 4.8, the output is exactly the same as in MultiplicationTable Here is the full source code listing for MultiplicationArray.java:
/*
* MultiplicationArray
* Prints the multiplication table using nested loops
* to loop on a multidimensional array
*/
public class MultiplicationArray { public static void main(String args[]) { int[][] mTable = new int[12][12];
//nested loop to build the array for (int i=1; i <=12; i++) { for (int j=1; j <= 12; j++) { mTable[i - 1][j - 1] = i * j;
} } //nested loop to print the array for (int i=0; i < mTable.length; i++) { System.out.print(‘\n’);
for (int j=0; j < mTable[i].length; j++) { System.out.print((mTable[i][j] + “ “).substring(0, 5));
} } } }
107
i o
FIGURE 4.8
You’re using nested loops to print multidimensional arrays!