1
Tutorial 10 – Interest Calculator
Application
Introducing the for Repetition Statement
Outline
10.1
10.2
10.3
10.4
10.5
10.6
Test-Driving the Interest Calculator Application
Essentials of Counter Controlled Repetition
Introducing the for Repetition Statement
Examples Using the for Statement
Constructing the Interest Calculator Application
Wrap-Up
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
2
Objectives
• In this tutorial, you will learn to:
– Execute statements repeatedly with the for repetition
statement.
– Use the JSpinner component to obtain input within a
specified range of values.
– Add scrollbars to a JTextArea by placing the component
inside a JScrollPane.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
3
10.1 Test Driving the Interest Calculator
Application
Application Requirements
You are considering investing $1000.00 in a savings account that yields 5%
interest, and you want to forecast how your investment will grow. Assuming
that you will leave all interest on deposit, develop an application that will
calculate and print the amount of money in your account at the end of each
year over a period of n years. To compute these amounts, use the following
formula:
a = p (1 + r) n
where
p is the original amount of money invested (the principal)
r is the annual interest rate
n is the number of years
a is the amount on deposit at the end of the nth year.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
4
10.1 Test Driving the Interest Calculator
Application (Cont.)
Figure 10.1
Running the completed Interest Calculator application.
Click to increase the
number of years
JSpinner component
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Click to decrease the
number of years
5
10.1 Test Driving the Interest Calculator
Application (Cont.)
• Entering values into the application
– Enter 1000 in the Principal: JTextField
– Enter 5 in the Interest rate: JTextField
– Click the up arrow in the Years: JSpinner until the value
reads 10
– Click the Calculate JButton
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
6
10.1 Test Driving the Interest Calculator
Application (Cont.)
Figure 10.2
Completed Interest Calculator application (initial output).
JTextArea displays the
application results
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Scrollbar enables users
to view all information
in the JTextArea
7
10.1 Test Driving the Interest Calculator
Application (Cont.)
Figure 10.3
Completed Interest Calculator application (output after scrolling up).
Output not displayed
previously
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Using the mouse to
draw the scrollbar
8
10.1 Test Driving the Interest Calculator
Application (Cont.)
Figure 10.4
Output from valid input.
Valid input directly entered
by typing in the JSpinner
• Arrows do not allow the user to select a value higher than
10 or lower than 1
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
9
10.1 Test Driving the Interest Calculator
Application (Cont.)
Figure 10.5
Entering out-of-range input into a JSpinner.
Invalid input directly entered
by typing in the JSpinner
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
10
10.1 Test Driving the Interest Calculator
Application (Cont.)
Figure 10.6
Entering input of the wrong type into a JSpinner.
Invalid input directly entered
by typing in the JSpinner
• Clicking the Calculate JButton causes the JSpinner to
display the most recent valid value
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
11
10.2 Essentials of Counter-Controlled
Repetition
• Four essentials of counter-controlled repetition
– the name of the control variable (or loop counter)
– the initial value of the control variable
– the increment (or decrement)
– the condition that tests for the final value of the control
variable
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
12
10.2 Essentials of Counter-Controlled
Repetition (Cont.)
Figure 10.7
Counter-controlled repetition example.
int counter = 2; // repetition counter
while ( counter <= 5 )
{
months = 12 * counter; // calculate payment period
// get monthly payment
monthlyPayment = calculateMonthlyPayment(
monthlyInterest, months, loanAmount );
// insert result into JTextArea
paymentsJTextArea.append( "\n" + months + "\t" +
currency.format( monthlyPayment ) );
counter++; // increment counter
} // end while
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
13
10.2 Essentials of Counter-Controlled
Repetition (Cont.)
• Four elements of counter-controlled repetition
–
–
–
–
Name: counter
Initial value: 2
Increment: 1
Final value: 5
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
14
10.3 Introducing the for Repetition Statement
Figure 10.8 Code segment for the Car Payment Calculator
application that demonstrates the for loop.
for ( int counter = 2; counter <= 5; counter+= 1 )
{
months = 12 * counter; // calculate payment period
// get monthly payment
monthlyPayment = calculateMonthlyPayment(
monthlyInterest, months, loanAmount );
// insert result into JTextArea
paymentsJTextArea.append( "\n" + months + "\t" +
currency.format( monthlyPayment ) );
} // end for
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
15
10.3 Introducing the for Repetition Statement
• for statement header (for header)
– Specifies all four elements for counter-controlled repetition
• First expression: initial value, name
• Second expression: loop-continuation condition
• Third expression: increment
Figure 10.9
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
for header components.
16
10.3 Introducing the for Repetition Statement
(Cont.)
Figure 10.10
for repetition statement UML activity diagram.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
17
10.4 Examples Using the for Statement
1, 2, 3, …, 100
for ( int i = 1; i <= 100; i++ )
100, 99, 98, …, 1
for ( int i = 100; i >= 1; i-- )
7, 14, 21, …, 77
for ( int i = 7; i <= 77; i += 7 )
20, 18, 16, …, 2
for ( int i = 20; i >= 2; i -= 2 )
2, 5, 8, …, 20
for ( int i = 2; i <= 20; i += 3 )
99, 88, 77, …, 0
for ( int i = 99; i >= 0; i -= 11 )
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
18
10.5 Constructing the Interest Calculator
Application
Calculate the amount on deposit when the user clicks the Calculate JButton:
Get the values for the principal, interest rate and years entered by the user
Display a header in the JTextArea to label the output
For each year, starting at 1 and ending with the number of years entered,
Calculate and display the year
Calculate and display the current value of the investment
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
19
10.5 Constructing the Interest Calculator
Application (Cont.)
Action
Component
interestRateJLabel,
principalJLabel,
yearsJLabel,
yearlyBalanceJLabel
Calculate amount on deposit calculateJButton
Event
Label the application’s
fields
Get the value for the
principal entered by user
Get the value for the interest
rate entered by user
Get the values for the years
entered by user
Display a header in the
JTextArea to label the output
Display the year and current
value of the investment
Figure 10.11
principalJTextField
interestRateJTextField
yearsJSpinner
yearlyBalanceJTextArea
yearlyBalanceJTextArea
ACE table for Interest Calculator application.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
User clicks Calculate
JButton
20
10.5 Constructing the Interest Calculator
Application (Cont.)
• SpinnerNumberModel
– Specifies that a JSpinner will contain a range of numerical
values rather than other types of data, such as dates
– Arguments
•
•
•
•
First: initial values displayed in JSpinner
Second: minimum value
Third: maximum value
Fourth: step size (increment)
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
21
10.5 Constructing the Interest Calculator
Application (Cont.)
Figure 10.12 Specifying yearsJSpinner’s initial value to be 1,
its range of values to be 1 through 10 and its step size to be 1.
Creating a number JSpinner
and setting its range
Figure 10.13
Setting the bounds property of a JSpinner.
Setting the
yearsJSpinner’s
bounds property
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
22
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.14
JSpinner added to Interest Calculator application.
JSpinner component
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
23
10.5 Creating the Interest Calculator
Application (Cont.)
• JScrollPane
– Container
• Contains other components
– Causes scrollbars to appear
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
24
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.15
Setting the JTextArea’s editable property to false.
Setting
yearlyBalanceJTextArea’s
editable property
Figure 10.16 Adding yearlyBalanceJTextArea
to yearlyBalanceJScrollPane.
Adding scrollbars to
yearlyBalanceJTextArea
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
25
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.17
Adding a JScrollPane that will hold a JTextArea.
Setting
yearlyBalanceJTextArea’s
bounds property
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
26
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.18
JTextArea with a JScrollPane added to the application.
JTextArea displays
the application results
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Vertical scrollbar
(not visible)
27
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.19
Application code for retrieving and storing user input.
Retrieve user input
• The getValue method returns the value displayed in the
JSpinner as an Object
• Cast that Object to an Integer
• Convert that Integer to an int using the intValue
method
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
28
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.20
Application code for displaying a header in a JTextArea.
Placing header in the
JTextArea and creating
a DecimalFormat to
format dollar amounts
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
29
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.21
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Header output in the JTextArea.
30
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.22
Creating the for statement.
Empty for statement
• The for statement loops once for each year up to the value
selected by the user
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
31
10.5 Creating the Interest Calculator
Application (Cont.)
• Calculating the interest
– Use the formula:
• a = p (1 + r)n
– a : amount
– p : principal
– r : rate
– n : number of years
– To perform an exponential operation
• Use the Math.pow method
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
32
10.5 Constructing the Interest Calculator
Application (Cont.)
Figure 10.23
Application code for calculating interest amount.
Using Math method pow
to calculate the amount
on deposit after the
specified number of years
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
33
10.5 Constructing the Interest Calculator
Application (Cont.)
Figure 10.24
Appending output to yearlyBalanceJTextArea.
Appending one line of text to
the JTextArea. (Note the use
of the escape sequence \n to
create a new line and the
escape sequence \t to tab to
the next column.)
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
34
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.25
Completed application (with initial output).
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
35
10.5 Creating the Interest Calculator
Application (Cont.)
Figure 10.26
Completed application (with remainder of output).
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Tutorial 10: InterestCalculator.java
// Calculate the total value of an investment.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
36
Outline
InterestCalculator.ja
va
(1 of 7)
public class InterestCalculator extends JFrame
{
// JLabel and JTextField for principal invested
private JLabel principalJLabel;
private JTextField principalJTextField;
// JLabel and JTextField for interest rate
private JLabel interestRateJLabel;
private JTextField interestRateJTextField;
// JLabel and JTextField for the number of years
private JLabel yearsJLabel;
private JSpinner yearsJSpinner;
// JLabel and JTextArea display amount on deposit at
// the end of each year up to number of years entered
private JLabel yearlyBalanceJLabel;
private JTextArea yearlyBalanceJTextArea;
2004 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
37
// JScrollPane adds scrollbars to JTextArea for lengthy output
private JScrollPane yearlyBalanceJScrollPane;
// JButton calculates amount on deposit at the
// end of each year up to number of years entered
private JButton calculateJButton;
Outline
InterestCalculator.ja
va
(2 of 7)
// no-argument constructor
public InterestCalculator()
{
createUserInterface();
}
// create and position GUI components; register event handlers
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null );
2004 Prentice Hall, Inc.
All rights reserved.
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// set up principalJLabel
principalJLabel = new JLabel();
principalJLabel.setBounds( 16, 16, 56, 24 );
principalJLabel.setText( "Principal:" );
contentPane.add( principalJLabel );
// set up principalJTextField
principalJTextField = new JTextField();
principalJTextField.setBounds( 100, 16, 100, 24 );
principalJTextField.setHorizontalAlignment(
JTextField.RIGHT );
contentPane.add( principalJTextField );
38
Outline
InterestCalculator.ja
va
(3 of 7)
// set up interestRateJLabel
interestRateJLabel = new JLabel();
interestRateJLabel.setBounds( 16, 56, 80, 24 );
interestRateJLabel.setText( "Interest rate:" );
contentPane.add( interestRateJLabel );
// set up interestRateJTextField
interestRateJTextField = new JTextField();
interestRateJTextField.setBounds( 100, 56, 100, 24 );
interestRateJTextField.setHorizontalAlignment(
JTextField.RIGHT );
contentPane.add( interestRateJTextField );
2004 Prentice Hall, Inc.
All rights reserved.
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
39
Outline
// set up yearsJLabel
yearsJLabel = new JLabel();
yearsJLabel.setBounds( 16, 96, 48, 24 );
yearsJLabel.setText( "Years:" );
contentPane.add( yearsJLabel );
InterestCalculator.ja
va
(4 of 7)
// set up yearsJSpinner
yearsJSpinner = new JSpinner(
new SpinnerNumberModel( 1, 1, 10, 1 ) );
yearsJSpinner.setBounds( 100, 96, 100, 24 );
contentPane.add( yearsJSpinner );
Setting the range
of your JSpinner
// set up yearlyBalanceJLabel
yearlyBalanceJLabel = new JLabel();
yearlyBalanceJLabel.setBounds( 16, 136, 150, 24 );
yearlyBalanceJLabel.setText( "Yearly account balance:" );
contentPane.add( yearlyBalanceJLabel );
// set up yearlyBalanceJTextArea
yearlyBalanceJTextArea = new JTextArea();
yearlyBalanceJTextArea.setEditable( false );
Customizing the
bounds property of
yearsJSpinner
Setting
yearlyBalanceJTextArea’s
editable property to false
2004 Prentice Hall, Inc.
All rights reserved.
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// set up yearlyBalanceJScrollPane
yearlyBalanceJScrollPane = new JScrollPane(
yearlyBalanceJTextArea );
yearlyBalanceJScrollPane.setBounds( 16, 160, 300, 92 );
contentPane.add( yearlyBalanceJScrollPane );
// set up calculateJButton
calculateJButton = new JButton();
calculateJButton.setBounds( 216, 16, 100, 24 );
calculateJButton.setText( "Calculate" );
contentPane.add( calculateJButton );
calculateJButton.addActionListener(
40
Outline
InterestCalculator.ja
va
(5 of 7)
Adding a JTextArea
to a JScrollPane and
setting the bounds of
the JScrollPane
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is clicked
public void actionPerformed( ActionEvent event )
{
calculateJButtonActionPerformed( event );
}
} // end anonymous inner class
); // end call to addActionListener
2004 Prentice Hall, Inc.
All rights reserved.
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
41
// set properties of window
setTitle( "Interest Calculator" ); // set window title
setSize( 340, 296 );
// set window size
setVisible( true );
// display window
Outline
} // end method createUserInterface
InterestCalculator.ja
va
(6 of 7)
// calculate and display amounts
private void calculateJButtonActionPerformed( ActionEvent event )
{
// declare variables to store user input
String principalText = principalJTextField.getText();
double principal = Double.parseDouble( principalText );
String rateText = interestRateJTextField.getText();
double rate = Double.parseDouble( rateText );
Retrieving user input
Integer integerObject = ( Integer ) yearsJSpinner.getValue();
int year = integerObject.intValue();
yearlyBalanceJTextArea.setText( "Year\tAmount on Deposit" );
DecimalFormat dollars = new DecimalFormat( "$0.00" );
Displaying the header
for output and creating
an object to format the
remainder of the output
2004 Prentice Hall, Inc.
All rights reserved.
42
145
// calculate the total value for each year
146
for ( int count = 1; count <= year; count++ )
147
{
148
double amount =
InterestCalculator.ja
149
principal * Math.pow( ( 1 + rate / 100 ), count );
va
150
yearlyBalanceJTextArea.append( "\n" + count + "\t" +
(7 of 7)
151
dollars.format( amount ) );
152
153
} // end for
154
155
} // end method calculateJButtonActionPerformed
156
Using a for statement to
157
// main method
calculate the amount on
158
public static void main( String args[] )
deposit and append this
159
{
160
InterestCalculator application = new InterestCalculator(); data to our JTextArea
161
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
162
163
} // end method main
164
165 } // end class InterestCalculator
Outline
2004 Prentice Hall, Inc.
All rights reserved.
© Copyright 2026 Paperzz