CSc 2310: Principle of Programming g( (Java) Spring 2013 Java Programming: from the Beginning Chapter 8 More Control Structures 1 Copyright 2000 W. W. Norton & Company. All rights reserved.
81 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. 2
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 3
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 4
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. 5
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-typetype identifier) block exception-type specifies what kind of exception the catch block should handle. identifier is an arbitrary name. 6
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"); 7
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() 8
Accessing Information About an Exception An example of printing the message inside an exception object: try { quotient = dividend / divisor; catch (ArithmeticException cept 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. 9
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. 10
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 y 1) to System.exit. 11
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. 12
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. 13
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 d 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. 14
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. 15
Checked Exceptions Versus Unchecked Exceptions Calling Thread.sleep outside a try block will cause the compiler to display a message saying that InterruptedExceptiond i must be caught. h 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) { 16
82 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( println("friday"); else if (day == 7) System.out.println("Saturday"); 17
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. 18
The switch Statement An equivalent switch statement: switch (day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println( 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"); Saturday break; 19
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. 20
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. 21
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; 22
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"); t ee break; 23
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; 24
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 lbl labels, the word default: can be used as a label. lbl 25
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; 26
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. 27
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 lbl labels. Any number of statements (including none at all) can go after each case label. Normally, the last statement in each case is break. 28
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; 29
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. 30
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 i = "Athens"; break; 31
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. 32
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. 33
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-expression 1 ) statement 1 else if (x == constant-expression 2 ) statement 2 else if (x == constant-expression 3 ) statement 3 34
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. 35
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"); i 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". 36
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. 37
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. 38
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); p 39
// 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; 40
// Display the number of days in the month System.out.println("There are " + numberofdays + " days in this month"); 41
83 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. 42
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. 43 Copyright 2000 W. W. Norton & Company. All rights reserved.
General Form of the do Statement Flow of control within a do statement: 44
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 + --i; while (i > 0); " and counting"); 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. 45
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. 46
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++; it n /= 10; while (n > 0); 47
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 i 1iteration i 2iteration i 3iteration i 4 numdigits 0 1 2 3 4 n 5392 539 53 5 0 When the loop terminates, numdigits has the value 4, which is the number of digits in 5392. 48
Finding the Number of Digits in an Integer A corresponding while loop: numdigits = 0; while (n > 0) { numdigits++; i n /= 10; If n is 0 initially, this loop won t execute at all, and numdigits will end up with the value 0. 49
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); 50
84 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. 51
Uses of the continue Statement Using continue can simplify the body of a loop by reducing the amount of nesting inside id the loop. Consider the following loop: while (expr1) { if (expr2) { statements A version that uses continue: while (expr1) { if (!expr2) continue; statements 52
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. 53
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 54
85 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. 55
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 { 56
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. 57
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; 58
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. 59
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; 60
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 efo operation to 1 ; break; case command 2 : Perform operation 2 ; break; case command n : Perform operation n ; break; default: Print error message; break; 61
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. 62
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. 63
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. 64