Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 20 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
20
Dung lượng
488,27 KB
Nội dung
Skipping 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 y is assigned the value 0, which is the value of x before it is incremented because that is the value of the postfix increment expression. On the other hand, the value of the b variable is 1, which is the value of a after 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 v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 4.3 The PrePost application demonstrates the difference between prefix and postfix increment operations. JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 98 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 99 C h a p t e r 4 U s i n g L o o p s a n d E x c e p t i o n H a n d l i n g The CountByFive Program The CountByFive program (shown in Figure 4.4) uses the compound increment assignment operator to increment the i variable 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(“, “); } } } INTHEREAL WORLD 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. JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 99 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Compound Assignment Operators The += operator used in the CountByFive program 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 variable is a variable of some primitive type, op is a mathematical oper- ator, and expression is 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 x becomes 6. It is initialized to 1, and then 5 is 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.9 is cast (converted to) the integer 5 before 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 String variable. String s = ““; s += 1; s += “, “; s += 2; s += ‘,’; s += “ buckle my shoe”; The value of s becomes “1, 2, buckle my shoe”. Here the code initializes s to 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. HINT 100 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 100 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Counting Backwards So far, every for loop you’ve encountered counts forwards, but you can also write a for loop 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 String objects 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 for loop 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 C h a p t e r 4 U s i n g L o o p s a n d E x c e p t i o n H a n d l i n g Operator Description Example Same Result as += Increment assignment operator x += 5; x = x + 5; –= Decrement assignment operator x –= 5; x = x – 5; *= Multiplication assignment operator x *= 5; x = x * 5; /= Division assignment operator x /= 5; x = x / 5; %= Modulus assignment operator x %= 5; x = x % 5; TABLE 4.1 COMPOUND ASSIGNMENT O PERATORS JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 101 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. for (int t=10; t > 0; t ) { System.out.print(t + “ “); } System.out.println(“\nBLASTOFF!”); } } 102 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 4.5 The CountDown program uses a for loop to count backwards. Making a for Loop Count Backwards In the CountDown program, you wrote a for loop that counts backwards from 10. In order to accomplish this, you initialize the t variable to the value 10. Remem- ber that in a for loop, 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 t is printed, its value is 10. You want this loop to terminate when t reaches zero, so you use the condition t > 0. Although t is greater than zero, this loop will continue to iter- ate. Each time through the loop you decrement t by 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 x before it is decremented by one. If the postfix operator is used (such as y = x––;), y will be assigned the value of x after it is decremented by one. JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 102 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Nested for Loops You can put any valid Java code within a for loop. 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 for loop. 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 NestedLoops program, 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 i variable in the outer loop is initialized to zero. Then the inner loop’s j variable is initialized to zero. This fact is illustrated in the first line of output. Then, j is incremented by one, so j = 1. Because the condition of the inner loop, j < 3 is still true, the body of the inner loop is exe- cuted again. The second line of output shows that i is still zero and j is 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. i is 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 j is not less than three. Then i is incremented again. And the list goes on. 103 C h a p t e r 4 U s i n g L o o p s a n d E x c e p t i o n H a n d l i n g JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 103 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Another example of nesting loops is the MultiplicationTable program. It uses nested for loops 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 i variable of the outer loop counts from 1 to 12 and so does the j variable 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 * j and 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 String method 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 v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 4.6 The NestedLoops program demonstrates nesting loops. JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 104 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. In this program, the first argument is 0 and 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 C h a p t e r 4 U s i n g L o o p s a n d E x c e p t i o n H a n d l i n g 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. INTHEREAL WORLD 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. JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 105 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. What 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 for loop 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 for loops 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 my2Darray is 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 my2Darray at index i. Got more than a two-dimensional array? No problem. Just nest another for loop. There is a one to one ratio of nested for loops 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 v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 106 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. for (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 MultiplicationTable program 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 C h a p t e r 4 U s i n g L o o p s a n d E x c e p t i o n H a n d l i n g FIGURE 4.8 You’re using nested loops to print multidimensional arrays! JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 107 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]...JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 108 108 Java Programming for the Absolute Beginner Using the while Loop You use the for loop when you know how many times you need to loop or are counting something You use the while loop when you don’t know how many times you need to loop Such as when you are performing searches within an array You don’t know... statement: Chapter 4 else { System.out.println(“I found Love at index “ + place); } JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 110 Java Programming for the Absolute Beginner 110 FIGURE 4.9 Looking for “Love” in allTheWrongPlaces inside a while loop user input First you print a message that prompts the user, such as “Item number:”, for example Then you accept user input You definitely want to print the prompt... it!”); } } while (!correct); } catch (IOException ioe) {} JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 112 112 Java Programming for the Absolute Beginner Preventing Endless Loops As you’ve seen, loops continue to iterate until the condition that causes the loop to continue becomes false If the condition never becomes false, the loop will continue forever This is known as an endless or infinite loop and... point of a specific enclosing loop Here is an example: JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 116 116 Java Programming for the Absolute Beginner Exception Handling Exception handling describes a way to handle certain situations, called exceptions, which would otherwise cause your program to crash Exceptions can occur when errors are encountered For example, the ArrayIndexOutOfBoundsException exception... an error after it has already been compiled and is currently running Chapter 4 while (true) { System.out.print(“true”); break; } System.out.println(“ Out of Loop”); JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 114 Java Programming for the Absolute Beginner 114 ghi: { System.out.println(“in ghi”); if (b) break ghi; System.out.println(“still in ghi”); } System.out.println(“out ghi”); } System.out.println(“out... must be a possibility for the condition to become false, or the loop will continue forever The break and continue Statements The break statement transfers control out of an enclosing statement In other words, it is used to break out of a loop explicitly This means that it takes control out of a switch, while, do, or for statement It must appear within a switch, while, do, or for statement or a compile-time... this Here is the source code for JokeTeller .java: /* * JokeTeller * Demonstrates use of the do-while loop */ import java. io.*; public class JokeTeller { public static void main(String args[]) { BufferedReader reader; String answer = “TO GET TO THE OTHER SIDE”; String response; boolean correct; reader = new BufferedReader(new InputStreamReader(System.in)); TEAM LinG - Live, Informative, Non-cost and Genuine!... desired value, so you continue to search for it until you find it In other words, while you haven’t found the right value yet, keep looking for it A while loop takes one condition that evaluates to either true or false and the loop continues to iterate as long as the condition is true Unlike the for loop, there is no initialization or incrementing The syntax for the while loop is as follows: while (condition)... number, it can’t be parsed by the Integer.parseInt() method It causes a NumberFormatException exception to occur The InputChecker program demonstrates how to make sure you get valid numbers from the users Here is a source listing for InputChecker .java: /* * InputChecker * Filters user input using exceptions and loops */ import java. io.*; public class InputChecker { public static void main(String args[])... //looking for love in allTheWrongPlaces System.out.println(“Looking for Love ”); while (!found) { found = allTheWrongPlaces[place] == “Love”; if (!found) { System.out.println(“Not at index “ + place); place++; } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 109 109 } } } found = . ^= 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. follow this URL: http:/ /java. sun.com/docs/ books/jls/second_edition/html/j.title .doc. html. HINT 100 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-04.qxd. but you can also write a for loop 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