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. In many cases, the program will terminate immediately. Java provides an exception handling to detect that an exception has occurred and execute statements that are designed to deal with the problem. Copyright © 2000 W. W. Norton & Company. All rights reserved.
3
Handle Exceptions Exception Handling: ArithmeticException
try{ i = j % k;} catch(ArithmeticException e){ System.out.println(“Error: / by zero); NullPointerException acct.deposit(100.00);} catch(NullPointerException e){ System.out.println(“Error: null point); } NumberFormatException try { n = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println(“Error: Not an integer); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
4
Handle Exceptions 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 : 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.
5
Variables and try Blocks
For example: int quotient; try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } Not complied. How to correct? The solution is often to assign a default value to the variable: int quotient = 0; // Default value Copyright © 2000 W. W. Norton & Company. All rights reserved.
6
Accessing Information About an Exception
The identifier in a catch block (typically e) represents this object. Every exception object contains a string. For example: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } If the exception is thrown, the message might be: / by zero Copyright © 2000 W. W. Norton & Company. All rights reserved.
7
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. try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); System.exit(-1); } Copyright © 2000 W. W. Norton & Company. All rights reserved.
8
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.
9
The throw Statement You can define an exception.
Exceptions are thrown using the throw statement. Typically use if, else, statement to define an exception. Example: Can_I_drive.java Design of Can_I_drive If you are younger than 16, print “You are too young for insurance” Age is less than 20, than return 1000. Age is not less than 20, return 600. Copyright © 2000 W. W. Norton & Company. All rights reserved.
10
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. For example, Thread.sleep method should be used with InterruptedException handling. try { Thread.sleep(100); } catch (InterruptedException e) {} Copyright © 2000 W. W. Norton & Company. All rights reserved.
11
Checked Exceptions Versus Unchecked Exceptions
An unchecked exception can be ignored by the programmer; there’s no need to use try and catch to handle the exception. For example: ArithmeticException, NullPointerException, and NumberFormatException. Copyright © 2000 W. W. Norton & Company. All rights reserved.
12
Using Exceptions Properly
Exceptions should be used when it’s not possible to test for errors before performing an operation. Division by zero is easy to detect, so do not use exceptions. Integer.parseInt is not easy to test before, so better use exceptions. Copyright © 2000 W. W. Norton & Company. All rights reserved.
13
8.2 The switch Statement A cascaded if statement can be replaced using switch statement: 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.
14
The switch Statement switch ( controlling expression ) {
case constant-expression : statements; break; … default : statements; break; // is not required } Copyright © 2000 W. W. Norton & Company. All rights reserved.
15
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.
16
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.
17
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.
18
Combining Case Labels Or, much shorter: 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.
19
The General Form of the switch Statement
In general, the switch statement has the following appearance: switch ( controlling expression ) { case constant-expression : statements; break; … default : statements; break; // is not required } A constant expression is an expression whose value can be determined by the compiler. This is called a case labels. Copyright © 2000 W. W. Norton & Company. All rights reserved.
20
The General Form of the switch Statement
Case labels don’t have to go in any particular 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.
21
Advantages of the switch Statement
The switch statement has two primary advantages over the cascaded if statement. It can make a program easier to understand. It is often faster than a cascaded if statement. Copyright © 2000 W. W. Norton & Company. All rights reserved.
22
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.
23
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.
24
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.
25
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 Copyright © 2000 W. W. Norton & Company. All rights reserved.
26
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.
27
General Form of the do Statement
while ( expression ) ; Copyright © 2000 W. W. Norton & Company. All rights reserved.
28
An Example of a do Statement
“countdown” example of Section 4.7 i = 10; While (i>0){ { System.out.println("T minus " + i + " and counting"); --i; } rewrite using a do statement: do { } while (i > 0); Difference: do statement is always executed at least once. Copyright © 2000 W. W. Norton & Company. All rights reserved.
29
When to choose do over while?
Finding the number of digits in an integer numDigits = 0; do { numDigits++; n /= 10; } while (n > 0); Rewrite to while statement while (n > 0) { } Problem? What if n = 0? Copyright © 2000 W. W. Norton & Company. All rights reserved.
30
Using Braces in do Statements
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); Program works fine, but readers can make mistake. Copyright © 2000 W. W. Norton & Company. All rights reserved.
31
8.4 The continue Statement
break vs. continue break terminates the loop. continue jumps to the end of the loop body, and the loop continues to execute. break is used more often than continue Advantage of continue : simplify the loop Copyright © 2000 W. W. Norton & Company. All rights reserved.
32
The continue Statement
Usage. Consider the following loop: while (expr1) { if (expr2) { statements } A version that uses continue: while (expr1) { if (!expr2) continue; statements } Copyright © 2000 W. W. Norton & Company. All rights reserved.
33
//Check a valid SSN input 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.
34
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.
35
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.
36
Uses of Nested Loops Typical situations: PrintInterest.java
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. (Insertion Sort 13.4) Copyright © 2000 W. W. Norton & Company. All rights reserved.
37
Labeled break Statements
When these statements are nested, the normal break statement can escape only one level of nesting. At times, there is a need for a break statement that can break out of multiple levels of nesting. Java’s labeled break statement can handle situations like this: break identifier ; For example: BreakWithLabelDemo.java Copyright © 2000 W. W. Norton & Company. All rights reserved.
38
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.
39
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. Enter interest rate: 6 Enter number of years: 5 Years 6% 7% 8% 9% 10% Copyright © 2000 W. W. Norton & Company. All rights reserved.
40
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.
41
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: March 2010 Copyright © 2000 W. W. Norton & Company. All rights reserved.
42
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.
43
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.
44
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.
45
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.
46
Stack Traces 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
© 2025 SlidePlayer.com Inc.
All rights reserved.