Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.

Similar presentations


Presentation on theme: "© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment."— Presentation transcript:

1 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment Calculator Application 24.2Introduction to Exception Handling 24.3Exception Handling in Java 24.4Java Exception Hierarchy 24.5Constructing the Enhanced Car Payment Calculator Application 24.6Wrap-Up Tutorial 24 – Enhanced Car Payment Calculator Application Introducing Exception Handling

2 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Objectives In this tutorial, you will learn to: –Understand exception handling –Use the try block, the catch block, the finally block and the throws clause to handle exceptions. –Understand the exception inheritance hierarchy. –Distinguish checked and unchecked exceptions.

3 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 3 24.1 Test-Driving the Enhanced Car Payment Calculator Application

4 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 4 24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.1 Running the completed Enhanced Car Payment Calculator application.

5 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 5 24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.2 Entering a double in the Down payment: JTextField.

6 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 6 24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.3 Message dialog displayed for incorrect down payment input.

7 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7 24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.4 Entering a non-numeric character in the Down payment: JTextField.

8 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 8 24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.5 Entering a non-numeric character in the Annual interest rate: JTextField.

9 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 9 24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.6 Displaying monthly payments after input is corrected.

10 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 10 24.2Introduction to Exception Handling Perform a task If the preceding task did not execute correctly Perform error processing Perform next task If the preceding task did not execute correctly Perform error processing …

11 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 24.2Introduction to Exception Handling (Cont.) A method throws an exception –A problem occurs during the method execution –Unable to correct the problem Exception handler –Executes when the application detects an exception Uncaught exception –Does not have an exception handler –Might cause an application to terminate execution

12 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 12 24.3Exception Handling in Java try block –Statements that might cause exceptions –Statements that should not execute if an exception occurs Catch block –Exception parameter Interact with the caught exception finally block –Always executes throws clause –Specifies the exceptions the method throws –Appears after the parameter list and before the method body

13 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 13 24.4Java Exception Hierarchy Throwable class –Superclass of all exceptions –Only these objects can be used with the exception-handling mechanism –Exception subclass of Throwable class Should be caught by the application –Error subclass of Throwable class Should not be caught by applications

14 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 14 24.4Java Exception Hierarchy (Cont.) Figure 24.7 Inheritance hierarchy for class Throwable.

15 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 15 24.4Java Exception Hierarchy (Cont.) Checked Exception –Are not subclasses of RuntimeException Unchecked Exception –Are subclasses of RuntimeException catch-or-declare requirement –Compiler checks whether the method throws checked exceptions –Compiler ensures that the checked exception is caught in a catch block

16 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 16 24.5 Constructing the Enhanced Car Payment Calculator Application When the user clicks the Calculate JButton Clear the JTextArea of any previous text Get the car price from the priceJTextField Get the down payment from the downPaymentJTextField Get the annual interest rate from the interestRateJTextField If the user provided valid input Calculate the loan amount (price minus down payment) Calculate the monthly interest rate (annual interest rate divided by 1200) Else Display the error message dialog Calculate the monthly payment Initialize the loan length to two years While the loan length is less than or equal to five years Calculate the number of months (loan length times 12) Calculate the monthly payment based on loan amount, monthly interest rate and loan length in months Display the result Increment the loan length in years by one year

17 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 17 24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)

18 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 18 24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure 24.9 Obtaining the user input. Get int s from priceJTextField and downPayment- JTextField Get double from interestRate- JTextField NumberFormatException class –Subclass of RuntimeException –Thrown when the application cannot convert a string to a desired numeric type, such as int or double.

19 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 19 24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure 24.10 Creating a try statement in the calculateJButton event handler. Adding a try statement

20 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 20 24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure 24.11 Adding a catch block. Adding a catch block

21 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 21 24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure 24.12 Displaying an error message dialog. Displaying an error message dialog

22 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 22 24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure 24.13 Error message dialog displayed when NumberFormatException occurs.

23  2004 Prentice Hall, Inc. All rights reserved. Outline 23 CarPayment.java (1 of 9) 1 // Tutorial 24: CarPayment.java 2 // This application uses exception-handling to handle invalid input. 3 import java.awt.*; 4 import java.text.DecimalFormat; 5 import java.awt.event.*; 6 import javax.swing.*; 7 8 public class CarPayment extends JFrame 9 { 10 // JLabel and JTextField for price 11 private JLabel priceJLabel; 12 private JTextField priceJTextField; 13 14 // JLabel and JTextField for down payment 15 private JLabel downPaymentJLabel; 16 private JTextField downPaymentJTextField; 17 18 // JLabel and JTextField for interest rate 19 private JLabel interestRateJLabel; 20 private JTextField interestRateJTextField; 21 22 // JButton to calculate the monthly payments 23 private JButton calculateJButton; 24

24  2004 Prentice Hall, Inc. All rights reserved. Outline 24 CarPayment.java (2 of 9) 25 // JTextArea to display the monthly payments 26 private JTextArea monthlyPaymentsJTextArea; 27 28 // no-argument constructor 29 public CarPayment() 30 { 31 createUserInterface(); 32 } 33 34 // create and position GUI components; register event handlers 35 private void createUserInterface() 36 { 37 // get content pane and set layout to null 38 Container contentPane = getContentPane(); 39 40 // enable explicit positioning of GUI components 41 contentPane.setLayout( null ); 42 43 // set up priceJLabel 44 priceJLabel = new JLabel(); 45 priceJLabel.setBounds( 40, 24, 80, 21 ); 46 priceJLabel.setText( "Price:" ); 47 contentPane.add( priceJLabel ); 48

25  2004 Prentice Hall, Inc. All rights reserved. Outline 25 CarPayment.java (3 of 9) 49 // set up priceJTextField 50 priceJTextField = new JTextField(); 51 priceJTextField.setBounds( 184, 24, 56, 21 ); 52 priceJTextField.setHorizontalAlignment( JTextField.RIGHT ); 53 contentPane.add( priceJTextField ); 54 55 // set up downPaymentJLabel 56 downPaymentJLabel = new JLabel(); 57 downPaymentJLabel.setBounds( 40, 56, 96, 21 ); 58 downPaymentJLabel.setText( "Down payment:" ); 59 contentPane.add( downPaymentJLabel ); 60 61 // set up downPaymentJTextField 62 downPaymentJTextField = new JTextField(); 63 downPaymentJTextField.setBounds( 184, 56, 56, 21 ); 64 downPaymentJTextField.setHorizontalAlignment( 65 JTextField.RIGHT ); 66 contentPane.add( downPaymentJTextField ); 67 68 // set up interestRateJLabel 69 interestRateJLabel = new JLabel(); 70 interestRateJLabel.setBounds( 40, 88, 120, 21 ); 71 interestRateJLabel.setText( "Annual interest rate:" ); 72 contentPane.add( interestRateJLabel ); 73

26  2004 Prentice Hall, Inc. All rights reserved. Outline 26 CarPayment.java (4 of 9) 74 // set up interestRateJTextField 75 interestRateJTextField = new JTextField(); 76 interestRateJTextField.setBounds( 184, 88, 56, 21 ); 77 interestRateJTextField.setHorizontalAlignment( 78 JTextField.RIGHT ); 79 contentPane.add( interestRateJTextField ); 80 81 // set up calculateJButton 82 calculateJButton = new JButton(); 83 calculateJButton.setBounds( 92, 128, 94, 24 ); 84 calculateJButton.setText( "Calculate" ); 85 contentPane.add( calculateJButton ); 86 calculateJButton.addActionListener( 87 88 new ActionListener() // anonymous inner class 89 { 90 // event handler called when calculateJButton is clicked 91 public void actionPerformed( ActionEvent event ) 92 { 93 calculateJButtonActionPerformed( event ); 94 } 95

27  2004 Prentice Hall, Inc. All rights reserved. Outline 27 CarPayment.java (5 of 9) 96 } // end anonymous inner class 97 98 ); // end call to addActionListener 99 100 // set up monthlyPaymentsJTextArea 101 monthlyPaymentsJTextArea = new JTextArea(); 102 monthlyPaymentsJTextArea.setEditable( false ); 103 monthlyPaymentsJTextArea.setBounds( 28, 168, 232, 90 ); 104 contentPane.add( monthlyPaymentsJTextArea ); 105 106 // set properties of application’s window 107 setTitle( "Car Payment Calculator" ); // set title-bar string 108 setSize( 288, 302 ); // set window size 109 setVisible( true ); // display window 110 111 } // end method createUserInterface 112 113 // calculate the monthly car payments 114 private void calculateJButtonActionPerformed( ActionEvent event ) 115 { 116 // clear JTextArea 117 monthlyPaymentsJTextArea.setText( "" ); 118

28  2004 Prentice Hall, Inc. All rights reserved. Outline 28 CarPayment.java (6 of 9) 119 // try to retrieve price and down payment 120 try 121 { 122 // get an integer from priceJTextField 123 int price = Integer.parseInt( priceJTextField.getText() ); 124 125 // get an integer from downPaymentJTextField 126 int downPayment = 127 Integer.parseInt( downPaymentJTextField.getText() ); 128 129 // get a double from interestRateJTextField 130 double interest = 131 Double.parseDouble( interestRateJTextField.getText() ); 132 133 // create table of options over different periods of time 134 processData( price, downPayment, interest ); 135 } 136 catch ( NumberFormatException exception ) 137 { 138 // integers were not input in the JTextFields 139 JOptionPane.showMessageDialog( this, 140 "Please enter integers for the price and down\n" + 141 "payment and a decimal number for the interest", 142 "Number Format Error", JOptionPane.ERROR_MESSAGE ); 143 } 144 145 } // end method calculateJButtonActionPerformed Enclosing the code that may cause exceptions in a try block Add a catch block to handle Number- FormatException

29  2004 Prentice Hall, Inc. All rights reserved. Outline 29 CarPayment.java (7 of 9) 146 147 // process entered data and calculate payments over 148 // each time interval 149 private void processData( int price, int downPayment, 150 double interest ) 151 { 152 // calculate loan amount and monthly interest 153 int loanAmount = price - downPayment; 154 double monthlyInterest = interest / 1200; 155 156 // format to display monthlyPayment in currency format 157 DecimalFormat dollars = new DecimalFormat( "$0.00" ); 158 159 int years = 2; // repetition counter 160 161 // add header JTextArea 162 monthlyPaymentsJTextArea.append( "Months\tMonthly Payments" ); 163 164 // while years is less than or equal to five years 165 while ( years <= 5 ) 166 { 167 // calculate payment period 168 int months = 12 * years;

30  2004 Prentice Hall, Inc. All rights reserved. Outline 30 CarPayment.java (8 of 9) 169 170 // get monthlyPayment 171 double monthlyPayment = calculateMonthlyPayment( 172 monthlyInterest, months, loanAmount ); 173 174 // insert result into JTextArea 175 monthlyPaymentsJTextArea.append( "\n" + months + "\t" + 176 dollars.format( monthlyPayment ) ); 177 178 years++; // increment counter 179 180 } // end while 181 182 } // end method processData 183 184 // calculate monthlyPayment 185 private double calculateMonthlyPayment( double monthlyInterest, 186 int months, int loanAmount ) 187 { 188 double base = Math.pow( 1 + monthlyInterest, months ); 189 return loanAmount * monthlyInterest / ( 1 - ( 1 / base ) ); 190 191 } // end method calculateMonthlyPayment 192

31  2004 Prentice Hall, Inc. All rights reserved. Outline 31 CarPayment.java (9 of 9) 193 // main method 194 public static void main( String [] args ) 195 { 196 CarPayment application = new CarPayment(); 197 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 198 199 } // end method main 200 201 } // end class CarPayment


Download ppt "© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment."

Similar presentations


Ads by Google