Download presentation
Presentation is loading. Please wait.
Published byAndrea Grant Modified over 9 years ago
1
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 8 More Control Structures
2
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 2 8.1Exceptions When a Java program performs an illegal operation, an exception happens. If a program has no special provisions for dealing with exceptions, it will behave badly if one occurs. Java provides a way for a program to detect that an exception has occurred and execute statements that are designed to deal with the problem. This process is called exception handling.
3
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 3 Common Exceptions There are many kinds of exceptions, each with a different name. Common exceptions: –ArithmeticException –NullPointerException Trying to divide by zero causes an ArithmeticException : i = j / k; // ArithmeticException occurs if k = 0
4
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 4 Common Exceptions Using zero as the right operand in a remainder operation also causes an ArithmeticException : i = j % k; // ArithmeticException occurs if k = 0 Calling a method using an object variable whose value is null causes a NullPointerException : acct.deposit(100.00); // NullPointerException occurs if acct is null
5
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 5 Handling Exceptions When an exception occurs (is thrown), the program has the option of catching it. In order to catch an exception, the code in which the exception might occur must be enclosed in a try block. After the try block comes a catch block that catches the exception (if it occurs) and performs the desired action.
6
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 Handling Exceptions The try and catch blocks together form a single statement, which can be used anywhere in a program that a statement is allowed: try block catch ( exception-type identifier ) block exception-type specifies what kind of exception the catch block should handle. identifier is an arbitrary name.
7
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 7 Handling Exceptions If an exception is thrown within the try block, and the exception matches the one named in the catch block, the code in the catch block is executed. If the try block executes normally—without an exception—the catch block is ignored. An example of try and catch blocks: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); }
8
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 8 Variables and try Blocks Be careful when declaring variables inside a try (or catch ) block. A variable declared inside a block is always local to that block. An example: try { int quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } quotient is local to the try block; it can’t be used outside the try block.
9
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 Variables and try Blocks There’s another trap associated with try blocks. Suppose that the quotient variable is declared immediately before the try block: int quotient; try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } The compiler won’t allow the value of quotient to be accessed later in the program, because no value is assigned to quotient if the exception occurs.
10
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 10 Variables and try Blocks The solution is often to assign a default value to the variable: int quotient = 0; // Default value try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); }
11
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 11 Accessing Information About an Exception When an exception occurs, Java creates an “exception object” that contains information about the error. The identifier in a catch block (typically e ) represents this object. Every exception object contains a string. The getMessage method returns this string: e.getMessage()
12
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 12 Accessing Information About an Exception An example of printing the message inside an exception object: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } If the exception is thrown, the message might be: / by zero Printing the value returned by getMessage can be useful if it’s not clear what the error is or what caused it.
13
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 13 Terminating the Program After an Exception When an exception is thrown, it may be necessary to terminate the program. Ways to cause program termination: –Execute a return statement in the main method. –Call the System.exit method.
14
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 14 Terminating the Program After an Exception Adding a call of System.exit to a catch block will cause the program to terminate: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); System.exit(-1); } A program that terminates abnormally should supply a nonzero argument (typically –1) to System.exit.
15
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 15 Converting Strings to Integers Attempting to convert a string to an int value using Integer.parseInt may fail: –Converting "123" will succeed. –Converting "duh" will fail, causing a NumberFormatException to be thrown. A robust program should provide a catch block to handle the exception: try { n = Integer.parseInt(str); } catch (NumberFormatException e) { // Handle exception }
16
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 16 Converting Strings to Integers If the string contains user input, it’s often a good idea to have the user re-enter the input. Putting the try and catch blocks in a loop allows the user multiple attempts to enter a valid number: while (true) { SimpleIO.prompt("Enter an integer: "); String userInput = SimpleIO.readLine(); try { n = Integer.parseInt(userInput); break; // Input was valid; exit the loop } catch (NumberFormatException e) { System.out.println("Not an integer; try again."); }
17
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 Converting Strings to Integers The loop could be put inside a class method that prompts the user to enter a number and then returns the user’s input in integer form: private static int readInt(String prompt) { while (true) { SimpleIO.prompt(prompt); String userInput = SimpleIO.readLine(); try { return Integer.parseInt(userInput); } catch (NumberFormatException e) { System.out.println("Not an integer; try again."); }
18
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 Multiple catch Blocks A try block can be followed by more than one catch block: try { quotient = Integer.parseInt(str1) / Integer.parseInt(str2); } catch (NumberFormatException e) { System.out.println("Error: Not an integer"); } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } When an exception is thrown, the first matching catch block will handle the exception.
19
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 19 Checked Exceptions Versus Unchecked Exceptions Exceptions fall into two categories. A checked exception must be dealt with by the program. The compiler will produce an error if there is no try block and catch block to handle the exception. An unchecked exception can be ignored by the programmer; there’s no need to use try and catch to handle the exception.
20
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 20 Checked Exceptions Versus Unchecked Exceptions Some unchecked exceptions represent disasters so severe that there’s no hope of continuing program execution. Others represent errors that could potentially occur at hundreds of places in a program, including ArithmeticException, NullPointerException, and NumberFormatException. Checked exceptions represent conditions that the programmer should be able to anticipate and deal with.
21
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 Checked Exceptions Versus Unchecked Exceptions The Thread.sleep method may throw InterruptedException, which is a checked exception. Thread.sleep allows a program to “go to sleep” for a specified time interval: Thread.sleep(100); The sleep time is measured in milliseconds.
22
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 Checked Exceptions Versus Unchecked Exceptions Calling Thread.sleep outside a try block will cause the compiler to display a message saying that “ InterruptedException must be caught.” To avoid getting an error from the compiler, a call of Thread.sleep should be put in a try block: try { Thread.sleep(100); } catch (InterruptedException e) {}
23
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 23 Using Exceptions Properly try and catch blocks aren’t meant to be used as ordinary control structures. Exceptions should be used when it’s not possible to test for errors before performing an operation. There’s no easy way to test whether the characters in a string form a valid integer. The best way to find out is to call a conversion method, such as Integer.parseInt.
24
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 24 8.2The switch Statement A cascaded if statement can be used to test the value of an expression against a set of possible values: if (day == 1) System.out.println("Sunday"); else if (day == 2) System.out.println("Monday"); else if (day == 3) System.out.println("Tuesday"); else if (day == 4) System.out.println("Wednesday"); else if (day == 5) System.out.println("Thursday"); else if (day == 6) System.out.println("Friday"); else if (day == 7) System.out.println("Saturday");
25
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 25 The switch Statement There’s a better way to accomplish the same effect. Java’s switch statement is designed specifically for comparing a variable (or, more generally, an expression) against a series of possible values.
26
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 26 The switch Statement An equivalent switch statement: switch (day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; }
27
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 27 The switch Statement When a switch statement is executed, the expression in parentheses (the controlling expression) is evaluated. The value of the controlling expression is then compared with the values listed after the word case (the case labels). If a match is found, the statements after the matching case label are executed.
28
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 28 The switch Statement Each case ends with a break statement. Executing a break statement causes the switch statement to terminate. The program continues executing with the statement that follows the switch statement.
29
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 29 Combining Case Labels Several case labels may correspond to the same action: switch (day) { case 1: System.out.println("Weekend"); break; case 2: System.out.println("Weekday"); break; case 3: System.out.println("Weekday"); break; case 4: System.out.println("Weekday"); break; case 5: System.out.println("Weekday"); break; case 6: System.out.println("Weekday"); break; case 7: System.out.println("Weekend"); break; }
30
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 30 Combining Case Labels This statement can be shortened by combining cases whose actions are identical: switch (day) { case 1: case 7: System.out.println("Weekend"); break; case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); break; }
31
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 31 Combining Case Labels To save space, several case labels can be put on the same line: switch (day) { case 1: case 7: System.out.println("Weekend"); break; case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); break; }
32
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 32 The default Case If the value of the controlling expression in a switch statement doesn’t match any of the case labels, the switch statement is skipped entirely. To indicate a default action to occur whenever the controlling expression doesn’t match any of the case labels, the word default: can be used as a label.
33
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 33 The default Case An example of a default case: switch (day) { case 1: case 7: System.out.println("Weekend"); break; case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); break; default: System.out.println("Not a valid day"); break; }
34
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 34 The General Form of the switch Statement In general, the switch statement has the following appearance: switch ( expression ) { case constant-expression : statements … case constant-expression : statements default : statements } A constant expression is an expression whose value can be determined by the compiler.
35
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 35 The General Form of the switch Statement Case labels don’t have to go in any particular order, although it’s good style to put the labels in a logical order. The default label doesn’t have to go last, although that’s where most programmers put it. It’s illegal for the same value to appear in two case labels. Any number of statements (including none at all) can go after each case label. Normally, the last statement in each case is break.
36
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 36 Layout of the switch Statement There are at least two common ways to lay out a switch statement. One layout technique puts the first statement in each case on the same line as the case label: switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; break; case 2000: olympicSite = "Sydney"; break; case 2004: olympicSite = "Athens"; break; }
37
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 37 Layout of the switch Statement When there’s only one statement per case (not counting break ), programmers often save space by putting the break statement on the same line: switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; break; case 2000: olympicSite = "Sydney"; break; case 2004: olympicSite = "Athens"; break; } The other common layout involves putting the statements in each case under the case label, indenting them to make the case label stand out.
38
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 38 Layout of the switch Statement Example: switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; break; case 2000: olympicSite = "Sydney"; break; case 2004: olympicSite = "Athens"; break; }
39
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 39 Layout of the switch Statement Although this layout allows longer statements, it also increases the number of lines required for the switch statement. This layout is best used when there are many statements in each case or the statements are lengthy.
40
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 40 Advantages of the switch Statement The switch statement has two primary advantages over the cascaded if statement. Using switch statements instead of cascaded if statements can make a program easier to understand. Also, the switch statement is often faster than a cascaded if statement. As the number of cases increases, the speed advantage of the switch becomes more significant.
41
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 41 Limitations of the switch Statement The switch statement can’t replace every cascaded if statement. Also, a switch statement’s controlling expression must have type char, byte, short, or int.
42
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 42 The Role of the break Statement Each case in a switch statement normally ends with a break statement. If break isn’t present, each case will “fall through” into the next case: switch (sign) { case -1: System.out.println("Negative"); case 0: System.out.println("Zero"); case +1: System.out.println("Positive"); } If sign has the value –1, the statement will print "Negative", "Zero", and "Positive".
43
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 43 The Role of the break Statement The case labels in a switch statement are just markers that indicate possible places to enter the list of statements inside the braces. Omitting the break statement is sometimes a useful programming technique, but most of the time it’s simply a mistake. Putting a break statement at the end of the last case makes it easier (and less risky) to add additional cases.
44
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 44 Program: Determining the Number of Days in a Month The MonthLength program asks the user for a month (an integer between 1 and 12) and a year, then displays the number of days in that month: Enter a month (1-12): 4 Enter a year: 2003 There are 30 days in this month The program will use a switch statement to determine whether the month has 30 days or 31 days. If the month is February, an if statement will be needed to determine whether February has 28 days or 29 days.
45
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 45 MonthLength.java // Determines the number of days in a month import jpb.*; public class MonthLength { public static void main(String[] args) { // Prompt the user to enter a month SimpleIO.prompt("Enter a month (1-12): "); String userInput = SimpleIO.readLine(); int month = Integer.parseInt(userInput); // Terminate program if month is not between 1 and 12 if (month 12) { System.out.println("Month must be between 1 and 12"); return; } // Prompt the user to enter a year SimpleIO.prompt("Enter a year: "); userInput = SimpleIO.readLine(); int year = Integer.parseInt(userInput);
46
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 46 // Determine the number of days in the month int numberOfDays; switch (month) { case 2: // February numberOfDays = 28; if (year % 4 == 0) { numberOfDays = 29; if (year % 100 == 0 && year % 400 != 0) numberOfDays = 28; } break; case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; break; default: numberOfDays = 31; break; }
47
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 47 // Display the number of days in the month System.out.println("There are " + numberOfDays + " days in this month"); }
48
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 48 8.3The do Statement Java has three loop statements: while, do, and for. All three use a boolean expression to determine whether or not to continue looping. Which type of loop to use is mostly a matter of convenience. –for is convenient for counting loops. –while is convenient for most other kinds of loops.
49
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 49 General Form of the do Statement A do statement looks like a while statement in which the controlling expression and body have switched positions: do statement while ( expression ) ; The do statement behaves like the while statement, except that the controlling expression is tested after the body of the loop is executed.
50
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 50 General Form of the do Statement Flow of control within a do statement:
51
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 51 An Example of a do Statement The “countdown” example of Section 4.7 rewritten using a do statement: i = 10; do { System.out.println("T minus " + i + " and counting"); --i; } while (i > 0); The only difference between the do statement and the while statement is that the body of a do statement is always executed at least once.
52
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 52 Finding the Number of Digits in an Integer Although the do statement isn’t used as often as the while statement, it’s handy in some cases. One way to determine the number of digits in an integer is to use a loop to divide the integer by 10 repeatedly until it becomes 0. The number of divisions performed is the number of digits.
53
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 53 Finding the Number of Digits in an Integer The do statement is a better choice than the while statement, because every integer—even 0—has at least one digit. A do loop that computes the number of digits in the integer n : numDigits = 0; do { numDigits++; n /= 10; } while (n > 0);
54
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 54 Finding the Number of Digits in an Integer A trace of the loop, assuming that n has the value 5392 initially: Initial After After AfterAfter valueiteration 1iteration 2iteration 3iteration 4 numDigits 0 1 234 n 53925395350 When the loop terminates, numDigits has the value 4, which is the number of digits in 5392.
55
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 55 Finding the Number of Digits in an Integer A corresponding while loop: numDigits = 0; while (n > 0) { numDigits++; n /= 10; } If n is 0 initially, this loop won’t execute at all, and numDigits will end up with the value 0.
56
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 56 Using Braces in do Statements Many programmers use braces in all do statements, whether or not they’re needed A do statement without braces around its body can be mistaken for a while statement: do System.out.println("T minus " + i-- + " and counting"); while (i > 0);
57
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 57 8.4The continue Statement Java’s continue statement is similar to the break statement. Unlike break, executing a continue statement doesn’t cause a loop to terminate. Instead, it causes the program to jump to the end of the loop body. The break statement can be used in loops and switch statements; the use of continue is limited to loops. continue is used much less often than break.
58
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 58 Uses of the continue Statement Using continue can simplify the body of a loop by reducing the amount of nesting inside the loop. Consider the following loop: while ( expr1 ) { if ( expr2 ) { statements } A version that uses continue : while ( expr1 ) { if (! expr2 ) continue; statements }
59
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 59 Uses of the continue Statement The continue statement is especially useful for subjecting input to a series of tests. If it fails any test, continue can be used to skip the remainder of the loop. Testing a Social Security number for validity includes checking that it contains three digits, a dash, two digits, a dash, and four digits. The following loop won’t terminate until the user enters an 11-character string with dashes in the right positions.
60
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 60 while (true) { SimpleIO.prompt("Enter a Social Security number: "); ssn = SimpleIO.readLine(); if (ssn.length() < 11) { System.out.println("Error: Number is too short"); continue; } if (ssn.length() > 11) { System.out.println("Error: Number is too long"); continue; } if (ssn.charAt(3) != '-' || ssn.charAt(6) != '-') { System.out.println( "Error: Number must have the form ddd-dd-dddd"); continue; } break; // Input passed all the tests, so exit the loop }
61
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 61 8.5Nested Loops When the body of a loop contains another loop, the loops are said to be nested. Nested loops are quite common, although the loops often aren’t directly related to each other.
62
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 62 An Example of Nested Loops The PhoneDirectory program of Section 5.8 contains a while loop with the following form: while (true) { … if (command.equalsIgnoreCase("a")) { … } else if (command.equalsIgnoreCase("f")) { … for (int i = 0; i < numRecords; i++) { … } } else if (command.equalsIgnoreCase("q")) { … } else { … } … }
63
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 63 Uses of Nested Loops In many cases, one loop is nested directly inside another loop, and the loops are related. Typical situations: –Displaying tables. Printing a table containing rows and columns is normally done by a pair of nested loops. –Working with multidimensional arrays. Processing the elements of a multidimensional array is normally done using nested loops, with one loop for each dimension of the array. –Sorting. Nested loops are also common in algorithms that sort data into order.
64
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 64 Labeled break Statements The break statement transfers control out of the innermost enclosing loop or switch statement. When these statements are nested, the normal break statement can escape only one level of nesting. Consider the case of a switch statement nested inside a while statement: while (…) { switch (…) { … break; … }
65
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 65 Labeled break Statements The break statement transfers control out of the switch statement, but not out of the while loop. Similarly, if a loop is nested inside a loop, executing a break will break out of the inner loop, but not the outer loop. At times, there is a need for a break statement that can break out of multiple levels of nesting.
66
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 66 Labeled break Statements Consider the situation of a program that prompts the user to enter a command. After executing the command, the program asks the user to enter another command: while (true) { Prompt user to enter command ; Execute command ; }
67
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 67 Labeled break Statements A switch statement (or cascaded if statement) will be needed to determine which command the user entered: while (true) { Prompt user to enter command ; switch ( command ) { case command 1 : Perform operation 1 ; break; case command 2 : Perform operation 2 ; break; … case command n : Perform operation n ; break; default: Print error message ; break; }
68
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 68 Labeled break Statements The loop will terminate when the user enters a particular command (command n, say). The program will need a break statement that can break out of the loop, when the user enters the termination command. Java’s labeled break statement can handle situations like this: break identifier ; The identifier is a label chosen by the programmer. The label precedes the loop that should be terminated by the break. A colon must follow the label.
69
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 69 Labeled break Statements A corrected version of the command loop: commandLoop: while (true) { Prompt user to enter command ; switch ( command ) { case command 1 : Perform operation 1 ; break; case command 2 : Perform operation 2 ; break; … case command n : break commandLoop; default: Print error message ; break; } The label doesn’t have to precede a loop. It could label any statement, including an if or switch.
70
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 70 Labeled continue Statements The continue statement normally applies to the nearest enclosing loop. continue is allowed to contain a label, to specify which enclosing loop the statement is trying to affect: continue identifier ; The label must precede one of the enclosing loops. Executing the statement causes the program to jump to the end of that loop, without causing the loop to terminate.
71
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 71 Program: Computing Interest The PrintInterest program prints a table showing the value of $100 invested at different rates of interest over a period of years. The user will enter an interest rate and the number of years the money will be invested. The table will show the value of the money at one- year intervals—at that interest rate and the next four higher rates—assuming that interest is compounded once a year.
72
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 72 Program: Computing Interest An example showing the interaction between PrintInterest and the user: Enter interest rate: 6 Enter number of years: 5 Years 6% 7% 8% 9% 10% 1 106 107 108 109 110 2 112 114 117 119 121 3 119 123 126 130 133 4 126 131 136 141 146 5 134 140 147 154 161
73
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 73 Design of the PrintInterest Program Each row depends on the numbers in the previous row, indicating that an array will be needed to store the values in the current row. Nested for statements will be needed: –The outer loop will count from 1 to the number of years requested by the user. –The inner loop will increment the interest rate from its lowest value to its highest value.
74
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 74 PrintInterest.java // Prints a table showing the value of $100 invested at // different rates of interest over a period of years import jpb.*; public class PrintInterest { public static void main(String[] args) { // Initialize array so that all amounts are equal double[] amounts = new double[5]; for (int i = 0; i < amounts.length; i++) amounts[i] = 100.00; // Prompt user to enter interest rate SimpleIO.prompt("Enter interest rate: "); String userInput = SimpleIO.readLine(); int lowRate = Integer.parseInt(userInput);
75
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 75 // Prompt user to enter number of years SimpleIO.prompt("Enter number of years: "); userInput = SimpleIO.readLine(); int numYears = Integer.parseInt(userInput); // Print a heading for the table. Each column represents // a single interest rate. The lowest rate is the one // entered by the user. Four other rates are shown; each // is 1% higher than the previous one. System.out.print("\nYears"); for (int i = 0; i < amounts.length; i++) printField(lowRate + i + "%", 6); System.out.println();
76
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 76 // Print contents of table; each row represents one // year for (int year = 1; year <= numYears; year++) { printField(year + " ", 5); for (int i = 0; i < amounts.length; i++) { amounts[i] += (lowRate + i) / 100.0 * amounts[i]; printField("" + Math.round(amounts[i]), 6); } System.out.println(); } // Displays str in a field of the specified width, with // spaces added at the beginning if necessary private static void printField(String str, int width) { for (int i = str.length(); i < width; i++) System.out.print(" "); System.out.print(str); }
77
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 77 Fields The printField method is a helper whose job is to print a string in a “field” of a certain width. If the string’s length is less than the specified width, printField displays extra spaces before the string, so that the total number of characters printed (spaces plus the characters in the string) equals the width.
78
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 78 Fields The table is arranged into fields. Each line begins with a single 5-character field, followed by five 6- character fields: The columns in the table will still line up properly when the years become two-digit numbers and the dollar amounts increase to four or five digits.
79
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 79 8.6Case Study: Printing a One-Month Calendar The PrintCalendar program will automatically detect the current month and year, and then display a calendar for that month: May 2000 -------------------- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 The month and year will be centered over the calendar.
80
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 80 Design of the PrintCalendar Program An initial design: 1. Determine the current month and year. 2. Determine on which day of the week the current month begins. 3. Display the calendar. Step 1 requires the help of GregorianCalendar, a class that belongs to the java.util package. Step 2 can be done with a standard algorithm such as Zeller’s congruence. However, there’s an easier way to do this step using GregorianCalendar.
81
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 81 The GregorianCalendar Class A GregorianCalendar object created using a constructor with no arguments will contain the current time and date: GregorianCalendar date = new GregorianCalendar(); The get method can be used to access the time and date stored inside a GregorianCalendar object. get returns a single part of the time or date, encoded as an integer. It requires an argument specifying which part should be returned. The argument to get is a constant defined in the Calendar class (also part of java.util ).
82
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 82 The GregorianCalendar Class A partial list of the constants defined in the Calendar class: Name MeaningRange DATE Day of month 1–31 DAY_OF_WEEK Day of the week 1–7 HOUR Hour (12-hour clock) 0–11 HOUR_OF_DAY Hour (24-hour clock) 0–23 MINUTE Minutes 0–59 MONTH Month 0–11 SECOND Seconds 0–59 YEAR Year –
83
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 83 The GregorianCalendar Class A call of get that returns the current year: System.out.println("Current year: " + date.get(Calendar.YEAR)); The set method changes the information stored inside a GregorianCalendar object. Algorithm to determine the day of the week on which the current month began: –Call set to set the date to 1. –Call get to retrieve DAY_OF_WEEK.
84
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 84 Design of Step 3 A design for step 3: 1. Print a heading for the calendar. 2. Print the days in the current month. Two helper methods, printHeading and printDays, will be responsible for these steps.
85
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 85 Design of the printHeading Method A design for printHeading : 1. Convert the month number to a name. 2. Determine how many spaces to display before the month. 3. Print the month, year, and a row of dashes. The month number can be converted to a name by using it as an index into an array containing the names of all 12 months.
86
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 86 Design of the printHeading Method The number of spaces to display before the month depends on: –Width of calendar (20 characters) –Length of month name –Number of characters needed for year and space between month and year (5 total) A formula for the number of spaces: (20 – (number of characters for year and space) – (length of month name))/2 = ( 15 – (length of month name))/2
87
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 87 Design of the printDays Method The printDays method will need to perform the following steps: 1. Leave space for “empty days” at the beginning of the month. 2. Print the days in the current month. Step 1 can be a loop that prints three spaces for each “empty day.” The number of empty days depends on the day of the week for day 1 of the current month.
88
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 88 Design of the printDays Method Step 2 requires a loop with a counter going from 1 to the number of days in the month. The loop body will print the value of the counter. If the counter has only a single digit, the loop will print a space before and after the number; otherwise, it will print a space after the number. The loop body will need to test whether the counter represents a Saturday. If so, the following day will begin on a different output line.
89
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 89 Design of the printDays Method Which dates fall on Saturday depends on what the first day of the month is. –If the month begins on Sunday, then days 7, 14, 21, and 28 are Saturdays. –If the month begins on Monday, then days 6, 13, 20, and 27 are Saturdays. If dayOfWeek is the starting day for the month (where 0 dayOfWeek 6), then day is a Saturday if (dayOfWeek + day) % 7 equals 0.
90
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 90 PrintCalendar.java // Program name: PrintCalendar // Author: K. N. King // Written: 1998-05-07 // Modified: 1999-07-07 // // Displays a calendar for the current month. The calendar // has the following form: // // May 2000 // -------------------- // 1 2 3 4 5 6 // 7 8 9 10 11 12 13 // 14 15 16 17 18 19 20 // 21 22 23 24 25 26 27 // 28 29 30 31 // // The month name and year are centered over the calendar. import java.util.*; import jpb.*;
91
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 91 public class PrintCalendar { public static void main(String[] args) { // Determine the current date GregorianCalendar date = new GregorianCalendar(); // Adjust to first day of month date.set(Calendar.DATE, 1); // Determine the current month and year int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); // Determine the day of the week for the first day of the // current month int dayOfWeek = date.get(Calendar.DAY_OF_WEEK) - 1; // Print a heading for the calendar printHeading(month, year); // Print the body of the calendar printDays(dayOfWeek, daysInMonth(month, year)); }
92
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 92 /////////////////////////////////////////////////////////// // NAME: printHeading // BEHAVIOR: Prints a heading for a one-month calendar. // The heading consists of a month and year, // centered over a row of 20 dashes. // PARAMETERS: month - number representing a month (0-11) // year - the year // RETURNS: Nothing /////////////////////////////////////////////////////////// private static void printHeading(int month, int year) { // Convert the month number to a name final String[] MONTH_NAMES = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; String monthString = MONTH_NAMES[month]; // Determine how many spaces to display before the month int precedingSpaces = (15 - monthString.length()) / 2;
93
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 93 // Print the month, year, and row of dashes System.out.println(); for (int i = 1; i <= precedingSpaces; i++) System.out.print(" "); System.out.println(monthString + " " + year); System.out.println("--------------------"); }
94
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 94 /////////////////////////////////////////////////////////// // NAME: printDays // BEHAVIOR: Prints the days in a one-month calendar // PARAMETERS: dayOfWeek - day of week for first day in // month (0-6) // monthLength - number of days in month // RETURNS: Nothing /////////////////////////////////////////////////////////// private static void printDays(int dayOfWeek, int monthLength) { // Leave space for "empty days" at the beginning of the // month for (int i = 0; i < dayOfWeek; i++) System.out.print(" ");
95
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 95 // Display the calendar. Add a space before each // single-digit day so that columns will line up. Advance // to the next line after each Saturday date is printed. for (int day = 1; day <= monthLength; day++) { if (day <= 9) System.out.print(" " + day + " "); else System.out.print(day + " "); if ((dayOfWeek + day) % 7 == 0) System.out.println(); } // If the month did not end on a Saturday, terminate the // last line of the calendar with a new-line if ((dayOfWeek + monthLength) % 7 != 0) System.out.println(); }
96
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 96 /////////////////////////////////////////////////////////// // NAME: daysInMonth // BEHAVIOR: Computes the number of days in a month. // PARAMETERS: month - number representing a month (0-11) // year - the year // RETURNS: Number of days in the specified month in the // specified year /////////////////////////////////////////////////////////// private static int daysInMonth(int month, int year) { int numberOfDays = 31; // Add 1 to month; the result will be between 1 and 12 switch (month + 1) { case 2: // February numberOfDays = 28; if (year % 4 == 0) { numberOfDays = 29; if (year % 100 == 0 && year % 400 != 0) numberOfDays = 28; } break;
97
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 97 case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; break; } return numberOfDays; }
98
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 98 8.7Debugging When a program fails to catch an exception, the Java interpreter will print information about the nature and location of the exception. Knowing how to interpret this information makes debugging much easier and faster. Consider what happens if line 121 of the PrintCalendar program is if (year % 0 == 4) { instead of if (year % 4 == 0) {
99
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 99 Output of the Interpreter Output of the Java interpreter when the modified PrintCalendar program is executed: Exception in thread "main" java.lang.ArithmeticException: / by zero at PrintCalendar.daysInMonth(PrintCalendar.java:121) at PrintCalendar.main(PrintCalendar.java:42) What this message means: –An ArithmeticException occurred. –The exception occurred on line 121 of PrintCalendar.java. The method that was executing at the time was daysInMonth. –daysInMonth had been called on line 42 of main.
100
Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 100 Stack Traces When an exception is not caught, the Java interpreter displays a stack trace: a list showing what method was executing at the time of the exception, which method called it, and so on. Sometimes an exception will be thrown inside one of Java’s own methods, causing the interpreter to mention methods and files that belong to the Java API.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.