Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Control Structures

Similar presentations


Presentation on theme: "More Control Structures"— Presentation transcript:

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 Exercise Write the program to handle the exception of Scanner when calling nextInt(); Write a program to demonstrate the divide by zero exception, and print out a message if dividing by zero. Copyright © 2000 W. W. Norton & Company. All rights reserved.

20 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.

21 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.

22 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.

23 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.

24 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.

25 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.

26 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.

27 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.

28 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.

29 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.

30 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.

31 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.

32 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.

33 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.

34 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.

35 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.

36 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.

37 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.

38 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.

39 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.

40 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.

41 Exercise Implement the following method that returns the number of days in a month. public int numOfDays(int year, int month) Copyright © 2000 W. W. Norton & Company. All rights reserved.

42 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.

43 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.

44 // 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.

45 // 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.

46 8.3 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.

47 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.

48 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.

49 Re-write this program without using continue.
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 Re-write this program without using continue. Copyright © 2000 W. W. Norton & Company. All rights reserved.


Download ppt "More Control Structures"

Similar presentations


Ads by Google