• No results found

Tutorial 24 – Enhanced

N/A
N/A
Protected

Academic year: 2021

Share "Tutorial 24 – Enhanced"

Copied!
31
0
0

Loading.... (view fulltext now)

Full text

(1)

© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Outline

24.1 Test-Driving the Enhanced Car Payment Calculator Application 24.2 Introduction to Exception Handling

24.3 Exception Handling in Java 24.4 Java Exception Hierarchy

24.5 Constructing the Enhanced Car Payment Calculator Application 24.6 Wrap-Up

Tutorial 24 – Enhanced Car Payment Calculator Application

Introducing Exception Handling

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

24.1 Test-Driving the Enhanced Car Payment Calculator Application

Application Requirements

A bank wishes to prevent users from entering incorrect data on their car loans.

Although the application you developed in Tutorial 8 continues running when incorrect data is entered, it will not calculate the result. Alter the Car Payment Calculator application to allow users to enter only integers in the Price:

JTextField and Down payment: JTextField. If the user enters anything besides an integer (such as a double or any non-numeric data), a message should be displayed instructing the user to enter an integer. Similarly, users should be allowed to enter only double values in the Annual interest rate: JTextField. If the user enters anything besides a double, a message should be displayed instructing the user to enter a double value between 0.0 and 100.0. The interest rate should be entered such that an input of 5 is equal to 5%.

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

24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)

Figure 24.2 Entering a double in the Down payment: JTextField.

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

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)

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.

24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)

Figure 24.6 Displaying monthly payments after input is corrected.

(10)

24.2 Introduction 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.

24.2 Introduction 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)

24.3 Exception 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.

24.4 Java 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)

24.4 Java 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.

24.4 Java 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)

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

(17)

© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)

Action Component/Class Event/Method

Label all the application’s components priceJLabel,

downPaymentJLabel,

interestRateJLabel

Click the Calculate JButton calculateJButton User clicks

CalculateJButton

Clear the JTextArea monthlyPaymentsJTextArea

Get the car price priceJTextField

Get the down payment downPaymentJTextField

Get the annual interest rate interestRateJTextField

Display error message dialog

(JOptionPane.showMessageDialog)

JOptionPane

Display result monthlyPaymentsJTextArea

Figure 24.8 Enhanced Car Payment Calculator application ACE table.

(18)

24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)

Figure 24.9 Obtaining the user input.

Get ints 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.

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)

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.

24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)

Figure 24.12 Displaying an error message dialog.

Displaying an error message dialog

(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

CarPayment.java (1 of 9)

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)

Outline

CarPayment.java (2 of 9)

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

CarPayment.java (3 of 9)

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)

Outline

CarPayment.java (4 of 9)

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

CarPayment.java (5 of 9)

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)

Outline

CarPayment.java (6 of 9)

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

CarPayment.java (7 of 9)

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)

Outline

CarPayment.java (8 of 9)

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

CarPayment.java (9 of 9)

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

References

Related documents

Terry came to me and said, “I would like you become a vice president of our new university.” Right after the college of pharmacy was.. created, we created the college of

While in Table 3 we present a pooled specification, to increase the chances for the added variables to exert a significant impact, in unreported regressions we repeat the

4.12 Without prejudice to the “Bank’s” right to take any legal action(s) against the “Cardholder” for any remaining outstanding “New Balance”, together with costs and

The entire premise of a privileged access management system is to secure privileged accounts by periodi- cally scrambling their passwords, so that current password values are not

According to Mayo Clinic, their APA ap- proved fellowship offers “the skills and experience necessary to independently evaluate and treat complex psychological problems.”

The Objectives of the study were to investigate whether 400 µg inhaled salbutamol influences 3 km running time-trial perfor- mance and lung function in eucapnic voluntary hyperpnoea

The unique electronic properties of BLG pave the way for its application [6]. As shown in Figure 4, in order to deform the BLG from a gapless system to a semiconductor material,