Download presentation
Presentation is loading. Please wait.
1
More Control Structures
Chapter 8 More Control Structures Copyright © 2000 W. W. Norton & Company. All rights reserved.
2
8.1 Exceptions 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. In many cases, the program will terminate immediately. 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. 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 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 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. 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) exception-type specifies what kind of exception the catch block should handle. identifier is an arbitrary name. 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"); } 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. 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. 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"); } 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() 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. 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. 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. 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 } 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."); } 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."); } 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. 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. 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. 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. 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) {} 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. In most cases, it’s better to test for an error before it occurs rather than wait until it happens and then catch the resulting exception. Consider the following loop: while (n != 0) { r = m % n; m = n; n = r; } Copyright © 2000 W. W. Norton & Company. All rights reserved.
24
Using Exceptions Properly
The loop could be written in the following way: try { while (true) { r = m % n; m = n; n = r; } } catch (ArithmeticException e) {} The loop still works, but it’s harder to figure out when the loop will terminate. Also, the code is longer and more deeply nested. Copyright © 2000 W. W. Norton & Company. All rights reserved.
25
Using Exceptions Properly
Another disadvantage of using exceptions when they’re not strictly necessary: a catch block may catch exceptions that were never anticipated. For example, a catch block that catches ArithmeticException may end up handling errors other than just division by zero. Copyright © 2000 W. W. Norton & Company. All rights reserved.
26
Using Exceptions Properly
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. If Integer.parseInt detects a problem during the conversion, it throws an exception to notify the program of the error. Copyright © 2000 W. W. Norton & Company. All rights reserved.
27
8.2 The 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"); Copyright © 2000 W. W. Norton & Company. All rights reserved.
28
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
29
The switch Statement An equivalent switch statement: switch (day) {
case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); case 3: System.out.println("Tuesday"); case 4: System.out.println("Wednesday"); case 5: System.out.println("Thursday"); case 6: System.out.println("Friday"); case 7: System.out.println("Saturday"); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
30
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
31
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
32
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"); case 3: System.out.println("Weekday"); case 4: System.out.println("Weekday"); case 5: System.out.println("Weekday"); case 6: System.out.println("Weekday"); case 7: System.out.println("Weekend"); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
33
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"); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
34
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"); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
35
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
36
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"); default: System.out.println("Not a valid day"); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
37
The General Form of the switch Statement
In general, the switch statement has the following appearance: switch ( expression ) { case constant-expression : statements … default : statements } A constant expression is an expression whose value can be determined by the compiler. Copyright © 2000 W. W. Norton & Company. All rights reserved.
38
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
39
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"; case 2000: olympicSite = "Sydney"; case 2004: olympicSite = "Athens"; } Copyright © 2000 W. W. Norton & Company. All rights reserved.
40
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
41
Layout of the switch Statement
Example: switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; case 2000: olympicSite = "Sydney"; case 2004: olympicSite = "Athens"; } Copyright © 2000 W. W. Norton & Company. All rights reserved.
42
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
43
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
44
Limitations of the switch Statement
The switch statement can’t replace every cascaded if statement. To qualify for conversion to a switch, every test in a cascaded if must compare the same variable (or expression) for equality with a constant: if (x == constant-expression1) statement1 else if (x == constant-expression2) statement2 else if (x == constant-expression3) statement3 … Copyright © 2000 W. W. Norton & Company. All rights reserved.
45
Limitations of the switch Statement
If any value that x is being compared with isn’t constant, a switch statement can’t be used. If the cascaded if statement tests a variety of different conditions, it’s not eligible for switch treatment. A switch statement’s controlling expression must have type char, byte, short, or int. Copyright © 2000 W. W. Norton & Company. All rights reserved.
46
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". Copyright © 2000 W. W. Norton & Company. All rights reserved.
47
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
48
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
49
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 < 1 || 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); Copyright © 2000 W. W. Norton & Company. All rights reserved.
50
// 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) } break; case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; default: numberOfDays = 31; Copyright © 2000 W. W. Norton & Company. All rights reserved.
51
// Display the number of days in the month
System.out.println("There are " + numberOfDays + " days in this month"); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
52
8.3 The 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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
53
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
54
General Form of the do Statement
Flow of control within a do statement: Copyright © 2000 W. W. Norton & Company. All rights reserved.
55
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
56
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
57
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); Copyright © 2000 W. W. Norton & Company. All rights reserved.
58
Finding the Number of Digits in an Integer
A trace of the loop, assuming that n has the value 5392 initially: Initial After After After After value iteration 1 iteration 2 iteration 3 iteration 4 numDigits n When the loop terminates, numDigits has the value 4, which is the number of digits in 5392. Copyright © 2000 W. W. Norton & Company. All rights reserved.
59
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
60
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); Copyright © 2000 W. W. Norton & Company. All rights reserved.
61
8.4 The 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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
62
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: if (!expr2) continue; Copyright © 2000 W. W. Norton & Company. All rights reserved.
63
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
64
SimpleIO.prompt("Enter a Social Security number: ");
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"); if (ssn.charAt(3) != '-' || ssn.charAt(6) != '-') { System.out.println( "Error: Number must have the form ddd-dd-dddd"); break; // Input passed all the tests, so exit the loop Copyright © 2000 W. W. Norton & Company. All rights reserved.
65
8.5 Nested 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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
66
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 { Copyright © 2000 W. W. Norton & Company. All rights reserved.
67
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
68
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; } Copyright © 2000 W. W. Norton & Company. All rights reserved.
69
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
70
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; } Copyright © 2000 W. W. Norton & Company. All rights reserved.
71
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 command1: Perform operation1; break; case command2: Perform operation2; break; … case commandn: Perform operationn; break; default: Print error message; break; } Copyright © 2000 W. W. Norton & Company. All rights reserved.
72
Labeled break Statements
The loop will terminate when the user enters a particular command (commandn, 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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
73
Labeled break Statements
A corrected version of the command loop: commandLoop: while (true) { Prompt user to enter command; switch (command) { case command1: Perform operation1; break; case command2: Perform operation2; break; … case commandn: 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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
74
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
75
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
76
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% Copyright © 2000 W. W. Norton & Company. All rights reserved.
77
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
78
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] = ; // Prompt user to enter interest rate SimpleIO.prompt("Enter interest rate: "); String userInput = SimpleIO.readLine(); int lowRate = Integer.parseInt(userInput); Copyright © 2000 W. W. Norton & Company. All rights reserved.
79
// 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(); Copyright © 2000 W. W. Norton & Company. All rights reserved.
80
// 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) / * 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); Copyright © 2000 W. W. Norton & Company. All rights reserved.
81
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
82
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
83
8.6 Case 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 The month and year will be centered over the calendar. Copyright © 2000 W. W. Norton & Company. All rights reserved.
84
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
85
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). Copyright © 2000 W. W. Norton & Company. All rights reserved.
86
The GregorianCalendar Class
A partial list of the constants defined in the Calendar class: Name Meaning Range 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 – Copyright © 2000 W. W. Norton & Company. All rights reserved.
87
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
88
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
89
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
90
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 Copyright © 2000 W. W. Norton & Company. All rights reserved.
91
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
92
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
93
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
94
PrintCalendar.java // Program name: PrintCalendar
// Author: K. N. King // Written: // Modified: // // Displays a calendar for the current month. The calendar // has the following form: // May 2000 // // // // // // // The month name and year are centered over the calendar. import java.util.*; import jpb.*; Copyright © 2000 W. W. Norton & Company. All rights reserved.
95
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)); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
96
///////////////////////////////////////////////////////////
// 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; Copyright © 2000 W. W. Norton & Company. All rights reserved.
97
// 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(" "); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
98
///////////////////////////////////////////////////////////
// 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(" "); Copyright © 2000 W. W. Norton & Company. All rights reserved.
99
// 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) Copyright © 2000 W. W. Norton & Company. All rights reserved.
100
///////////////////////////////////////////////////////////
// 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) } break; Copyright © 2000 W. W. Norton & Company. All rights reserved.
101
case 4: // April case 6: // June case 9: // September
case 11: // November numberOfDays = 30; break; } return numberOfDays; Copyright © 2000 W. W. Norton & Company. All rights reserved.
102
8.7 Debugging 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) { Copyright © 2000 W. W. Norton & Company. All rights reserved.
103
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
104
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. Copyright © 2000 W. W. Norton & Company. All rights reserved.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.