Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting.

Similar presentations


Presentation on theme: "© 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting."— Presentation transcript:

1 © 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Dialog Boxes File Choosers and Color Choosers

2 © 2004 Pearson Addison-Wesley. All rights reserved10-2 Dialog Boxes A dialog box is a window that appears on top of any currently active window It may be used to:  convey information  confirm an action  allow the user to enter data  pick a color  choose a file A dialog box usually has a specific, solitary purpose, and the user interaction with it is brief

3 © 2004 Pearson Addison-Wesley. All rights reserved10-3 Dialog Boxes The JOptionPane class provides methods that simplify the creation of some types of dialog boxes See EvenOdd.java (page 262)EvenOdd.java

4 © 2004 Pearson Addison-Wesley. All rights reserved10-4 OddEven.java //************************************************************* // EvenOdd.java Author: Lewis/Loftus // // Demonstrates the use of the JOptionPane class. //************************************************************* import javax.swing.JOptionPane; public class EvenOdd { //---------------------------------------------------------- // Determines if the value input by the user is even or // odd. Uses multiple dialog boxes for user interaction. //---------------------------------------------------------- public static void main (String[] args) { String numStr, result, type; int num, again;

5 © 2004 Pearson Addison-Wesley. All rights reserved10-5 OddEven.java do { numStr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); if (num%2 == 0) type = "even"; else type = "odd"; result = "That number is " + type; JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); } while (again == JOptionPane.YES_OPTION); }

6 © 2004 Pearson Addison-Wesley. All rights reserved10-6 File Choosers Situations often arise where we want the user to select a file stored on a disk drive, usually so that its contents can be read and processed A file chooser, represented by the JFileChooser class, simplifies this process The user can browse the disk and filter the file types displayed See DisplayFile.java (page 516) DisplayFile.java

7 © 2004 Pearson Addison-Wesley. All rights reserved10-7 File Chooser Window

8 © 2004 Pearson Addison-Wesley. All rights reserved10-8 DisplayFile.java import java.util.Scanner; import java.io.*; import javax.swing.*; public class DisplayFile { //---------------------------------------------------------- // Opens a file chooser dialog, reads the selected file and // loads it into a text area. //---------------------------------------------------------- public static void main (String[] args) throws IOException { JFileChooser chooser = new JFileChooser(); int status = chooser.showOpenDialog (null); if (status != JFileChooser.APPROVE_OPTION) JOptionPane.showMessageDialog (null, "No File Chosen");

9 © 2004 Pearson Addison-Wesley. All rights reserved10-9 DisplayFile.java else { File file = chooser.getSelectedFile(); Scanner scan = new Scanner (file); String info = ""; while (scan.hasNext()) info += scan.nextLine() + "\n"; System.out.print (info); }

10 © 2004 Pearson Addison-Wesley. All rights reserved10-10 Summary Chapter 9 has focused on:  defining polymorphism and its benefits  using inheritance to create polymorphic references  using interfaces to create polymorphic references  using polymorphism to implement sorting and searching algorithms

11 Chapter 10 Exceptions

12 © 2004 Pearson Addison-Wesley. All rights reserved10-12 Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on:  the purpose of exceptions  exception messages  the try-catch statement  propagating exceptions  the exception class hierarchy

13 © 2004 Pearson Addison-Wesley. All rights reserved10-13 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions

14 © 2004 Pearson Addison-Wesley. All rights reserved10-14 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught

15 © 2004 Pearson Addison-Wesley. All rights reserved10-15 Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways:  ignore it  handle it where it occurs  handle it an another place in the program The manner in which an exception is processed is an important design consideration

16 © 2004 Pearson Addison-Wesley. All rights reserved10-16 Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that:  indicates the line on which the exception occurred  shows the method call trail that lead to the attempted execution of the offending line See Zero.java (page 533) Zero.java

17 © 2004 Pearson Addison-Wesley. All rights reserved10-17 Zero.java //************************************************************* // Zero.java Author: Lewis/Loftus // // Demonstrates an uncaught exception. //************************************************************* public class Zero { //---------------------------------------------------------- // Deliberately divides by zero to produce an exception. //---------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); }

18 © 2004 Pearson Addison-Wesley. All rights reserved10-18 Zero.java Output ----jGRASP exec: java Zero Exception in thread "main" java.lang.ArithmeticException: / by zero at Zero.main(Zero.java:17) ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete.

19 © 2004 Pearson Addison-Wesley. All rights reserved10-19 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions

20 © 2004 Pearson Addison-Wesley. All rights reserved10-20 The try Statement To handle an exception in a program, the line that throws the exception is executed within a try block A try block is followed by one or more catch clauses Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the exception type See ProductCodes.java (page 536) ProductCodes.java

21 © 2004 Pearson Addison-Wesley. All rights reserved10-21 ProductCodes.java import java.util.Scanner; public class ProductCodes { //---------------------------------------------------------- // Counts the number of product codes that are entered with // a zone of R and and district greater than 2000. //---------------------------------------------------------- public static void main (String[] args) { String code; char zone; int district, valid = 0, banned = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine();

22 © 2004 Pearson Addison-Wesley. All rights reserved10-22 ProductCodes.java while (!code.equals ("XXX")) { try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); }

23 © 2004 Pearson Addison-Wesley. All rights reserved10-23 ProductCodes.java System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); } System.out.println ("# of valid codes entered: " + valid); System.out.println ("# of banned codes entered: " + banned); } Enter product code (XXX to quit): 83745P Improper code length: 83745P Enter product code (XXX to quit): EJUTBYEHBT District is not numeric: EJUTBYEHBT Enter product code (XXX to quit): 174865847W Enter product code (XXX to quit): 374648364R Enter product code (XXX to quit): XXX # of valid codes entered: 2 # of banned codes entered: 1 Output

24 © 2004 Pearson Addison-Wesley. All rights reserved10-24 The finally Clause A try statement can have an optional clause following the catch clauses, designated by the reserved word finally The statements in the finally clause always are executed If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

25 © 2004 Pearson Addison-Wesley. All rights reserved10-25 Exception Propagation An exception can be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method A try block that contains a call to a method in which an exception is thrown can be used to catch that exception See Propagation.java (page 539) Propagation.java See ExceptionScope.java (page 540) ExceptionScope.java

26 © 2004 Pearson Addison-Wesley. All rights reserved10-26 Propagation.java //************************************************************* // Propagation.java Author: Lewis/Loftus // // Demonstrates exception propagation. //************************************************************* public class Propagation { //---------------------------------------------------------- // Invokes the level1 method to begin the exception // demonstration. //---------------------------------------------------------- static public void main (String[] args) { ExceptionScope demo = new ExceptionScope(); System.out.println("Program beginning."); demo.level1(); System.out.println("Program ending."); }

27 © 2004 Pearson Addison-Wesley. All rights reserved10-27 ExceptionScope.java public class ExceptionScope { //---------------------------------------------------------- // Catches and handles the exception that is thrown in // level3. //---------------------------------------------------------- public void level1() { System.out.println("Level 1 beginning."); try { level2(); } catch (ArithmeticException problem) { System.out.println (); System.out.println ("The exception message is: " + problem.getMessage()); System.out.println (); System.out.println ("The call stack trace:"); problem.printStackTrace(); System.out.println (); }

28 © 2004 Pearson Addison-Wesley. All rights reserved10-28 ExceptionScope.java finally { System.out.println("***In the finally bit***"); } System.out.println("Level 1 ending."); } //---------------------------------------------------------- // Serves as an intermediate level. The exception // propagates through this method back to level1. //---------------------------------------------------------- public void level2() { System.out.println("Level 2 beginning."); level3 (); System.out.println("Level 2 ending."); }

29 © 2004 Pearson Addison-Wesley. All rights reserved10-29 ExceptionScope.java //---------------------------------------------------------- // Performs a calculation to produce an exception. It is // not caught and handled at this level. //---------------------------------------------------------- public void level3 () { int numerator = 10, denominator = 0; System.out.println("Level 3 beginning."); int result = numerator / denominator; System.out.println("Level 3 ending."); }

30 © 2004 Pearson Addison-Wesley. All rights reserved10-30 Propagation.java Output Program beginning. Level 1 beginning. Level 2 beginning. Level 3 beginning. The exception message is: / by zero The call stack trace: java.lang.ArithmeticException: / by zero at ExceptionScope.level3(ExceptionScope.java:59) at ExceptionScope.level2(ExceptionScope.java:46) at ExceptionScope.level1(ExceptionScope.java:19) at Propagation.main(Propagation.java:17) ***In the finally bit*** Level 1 ending. Program ending.

31 © 2004 Pearson Addison-Wesley. All rights reserved10-31 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions

32 © 2004 Pearson Addison-Wesley. All rights reserved10-32 The Exception Class Hierarchy Classes that define exceptions are related by inheritance, forming an exception class hierarchy All error and exception classes are descendents of the Throwable class A programmer can define an exception by extending the Exception class or one of its descendants The parent class is chosen based on how the new exception will be used

33 © 2004 Pearson Addison-Wesley. All rights reserved10-33 Checked Exceptions An exception is either checked or unchecked A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it A throws clause is appended to the method header The compiler will issue an error if a checked exception is not caught or asserted in a throws clause

34 © 2004 Pearson Addison-Wesley. All rights reserved10-34 Unchecked Exceptions An unchecked exception does not require explicit handling, though it could be processed that way The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants Errors are similar to RuntimeException and its descendants in that:  Errors should not be caught  Errors do not require a throws clause

35 © 2004 Pearson Addison-Wesley. All rights reserved10-35 The throw Statement Exceptions are thrown using the throw statement Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown See CreatingExceptions.java (page 543) CreatingExceptions.java See OutOfRangeException.java (page 544) OutOfRangeException.java

36 © 2004 Pearson Addison-Wesley. All rights reserved10-36 CreatingExceptions.java import java.util.Scanner; public class CreatingExceptions { //---------------------------------------------------------- // Creates an exception object and possibly throws it. //---------------------------------------------------------- public static void main (String[] args) throws OutOfRangeException { final int MIN = 25, MAX = 40; Scanner scan = new Scanner (System.in); OutOfRangeException problem = new OutOfRangeException ("Input value is out of range."); System.out.print ("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextInt();

37 © 2004 Pearson Addison-Wesley. All rights reserved10-37 CreatingExceptions.java // Determine if the exception should be thrown if (value MAX) throw problem; System.out.println ("End of main method."); // may never // reach }

38 © 2004 Pearson Addison-Wesley. All rights reserved10-38 OutOfRangeException.java //************************************************************* // OutOfRangeException.java Author: Lewis/Loftus // // Represents an exceptional condition in which a value is out // of some particular range. //************************************************************* public class OutOfRangeException extends Exception { //---------------------------------------------------------- // Sets up the exception object with a particular message. //---------------------------------------------------------- OutOfRangeException (String message) { super (message); }

39 © 2004 Pearson Addison-Wesley. All rights reserved10-39 Output ----jGRASP exec: java CreatingExceptions Enter an integer value between 25 and 40, inclusive: 25 End of main method. ----jGRASP: operation complete. ----jGRASP exec: java CreatingExceptions Enter an integer value between 25 and 40, inclusive: 24 Exception in thread "main" OutOfRangeException: Input value is out of range. at CreatingExceptions.main(CreatingExceptions.java:20) ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete.

40 © 2004 Pearson Addison-Wesley. All rights reserved10-40 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions

41 © 2004 Pearson Addison-Wesley. All rights reserved10-41 I/O Exceptions Let's examine issues related to exceptions and I/O A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information to an output stream A program can manage multiple streams simultaneously

42 © 2004 Pearson Addison-Wesley. All rights reserved10-42 Standard I/O There are three standard I/O streams:  standard output – defined by System.out  standard input – defined by System.in  standard error – defined by System.err We use System.out when we execute println statements System.out and System.err typically represent a particular window on the monitor screen System.in typically represents keyboard input, which we've used many times with Scanner objects

43 © 2004 Pearson Addison-Wesley. All rights reserved10-43 The IOException Class Operations performed by some I/O classes may throw an IOException  A file might not exist  Even if the file exists, a program may not be able to find it  The file might not contain the kind of data we expect An IOException is a checked exception

44 © 2004 Pearson Addison-Wesley. All rights reserved10-44 Writing Text Files In Chapter 5 we explored the use of the Scanner class to read input from a text file Let's now examine other classes that let us write data to a text file The FileWriter class represents a text output file, but with minimal support for manipulating data Therefore, we also rely on PrintStream objects, which have print and println methods defined for them

45 © 2004 Pearson Addison-Wesley. All rights reserved10-45 Writing Text Files Finally, we'll also use the PrintWriter class for advanced internationalization and error checking We build the class that represents the output file by combining these classes appropriately See TestData.java (page 547) TestData.java Output streams should be closed explicitly

46 © 2004 Pearson Addison-Wesley. All rights reserved10-46 TestData.java import java.io.*; public class TestData { //---------------------------------------------------------- // Creates a file of test data that consists of ten lines // each containing ten integer values in the range 10 to // 99. //---------------------------------------------------------- public static void main (String[] args) throws IOException { final int MAX = 10; int value; String file = "test.dat"; FileWriter fw = new FileWriter (file); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw);

47 © 2004 Pearson Addison-Wesley. All rights reserved10-47 TestData.java for (int line=1; line <= MAX; line++) { for (int num=1; num <= MAX; num++) { value = (int)(Math.random() * 90) + 10; outFile.print (value + " "); } outFile.println (); } outFile.close(); System.out.println ("Output file has been created: " + file); }

48 © 2004 Pearson Addison-Wesley. All rights reserved10-48 TestData.java Output 45 51 64 79 41 35 26 10 10 91 24 48 34 91 47 60 96 23 15 28 43 26 23 45 53 29 87 22 59 13 71 81 38 51 44 85 11 81 48 78 58 85 59 27 25 32 54 10 76 77 29 75 93 51 57 29 23 93 97 59 29 78 83 19 84 66 99 70 86 37 66 67 17 78 20 23 28 10 51 61 73 94 89 26 25 99 82 96 80 60 32 39 54 76 38 67 92 47 12 42 File: test.dat

49 © 2004 Pearson Addison-Wesley. All rights reserved10-49 Summary Chapter 10 has focused on: the purpose of exceptions exception messages the try-catch statement propagating exceptions the exception class hierarchy

50 © 2004 Pearson Addison-Wesley. All rights reserved10-50 Final Review Cumulative final Topics  arithmetic expressions integer division and casting  Writing classes  Boolean expressions  if-statements – Writing them and tracing paths through the code  loops (nested-loops) – Writing them, counting number of iterations  Using arrays  Testing code (white box testing)  Using the String class to parse user input  Recursion  Inheritance/Polymorphism  Sorting/Searching  Exceptions Study the self-review, exercises, and Chapter Quizzes in myCodeMate Study the midterm and homework


Download ppt "© 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting."

Similar presentations


Ads by Google