© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 10.1 Test-Driving the Interest Calculator Application 10.2 Essentials of Counter Controlled Repetition 10.3 Introducing the for Repetition Statement 10.4 Examples Using the for Statement 10.5Constructing the Interest Calculator Application 10.6Wrap-Up Tutorial 10 – Interest Calculator Application Introducing the for Repetition Statement
© Copyright 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test Driving the Interest Calculator Application
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test Driving the Interest Calculator Application (Cont.) Figure 10.1 Running the completed Interest Calculator application. Click to decrease the number of years JSpinner componentClick to increase the number of years
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test Driving the Interest Calculator Application (Cont.) Figure 10.2 Completed Interest Calculator application (initial output). JTextArea displays the application results Scrollbar enables users to view all information in the JTextArea
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test Driving the Interest Calculator Application (Cont.) Figure 10.3 Completed Interest Calculator application (output after scrolling up). Output not displayed previously Using the mouse to draw the scrollbar
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Essentials of Counter-Controlled Repetition (Cont.) 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 Figure 10.7 Counter-controlled repetition example.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Essentials of Counter-Controlled Repetition (Cont.) Four elements of counter-controlled repetition –Name: counter –Initial value: 2 –Increment: 1 –Final value: 5
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 for header components.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introducing the for Repetition Statement (Cont.) Figure for repetition statement UML activity diagram.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Examples Using the for Statement for ( int i = 1; i <= 100; i++ ) for ( int i = 100; i >= 1; i-- ) for ( int i = 7; i <= 77; i += 7 ) for ( int i = 20; i >= 2; i -= 2 ) for ( int i = 2; i <= 20; i += 3 ) for ( int i = 99; i >= 0; i -= 11 ) 1, 2, 3, …, , 99, 98, …, 1 7, 14, 21, …, 77 20, 18, 16, …, 2 2, 5, 8, …, 20 99, 88, 77, …, 0
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Interest Calculator Application (Cont.)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Interest Calculator Application (Cont.) Figure Specifying yearsJSpinner ’s initial value to be 1, its range of values to be 1 through 10 and its step size to be 1. Figure Setting the bounds property of a JSpinner. Setting the yearsJSpinner ’s bounds property Creating a number JSpinner and setting its range
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure JSpinner added to Interest Calculator application. JSpinner component
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) JScrollPane –Container Contains other components –Causes scrollbars to appear
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Setting the JTextArea ’s editable property to false. Setting yearlyBalanceJTextArea ’s editable property Figure Adding yearlyBalanceJTextArea to y earlyBalanceJScrollPane. Adding scrollbars to yearlyBalanceJTextArea
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Adding a JScrollPane that will hold a JTextArea. Setting yearlyBalanceJTextArea ’s bounds property
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure JTextArea with a JScrollPane added to the application. JTextArea displays the application results Vertical scrollbar (not visible)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Application code for displaying a header in a JTextArea. Placing header in the JTextArea and creating a DecimalFormat to format dollar amounts
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Header output in the JTextArea.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Creating the for statement. Empty for statement The for statement loops once for each year up to the value selected by the user
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Interest Calculator Application (Cont.) Figure Application code for calculating interest amount. Using Math method pow to calculate the amount on deposit after the specified number of years
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Interest Calculator Application (Cont.) Figure 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Completed application (with initial output).
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Creating the Interest Calculator Application (Cont.) Figure Completed application (with remainder of output).
2004 Prentice Hall, Inc. All rights reserved. Outline 36 InterestCalculator.ja va (1 of 7) 1 // Tutorial 10: InterestCalculator.java 2 // Calculate the total value of an investment. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 import java.text.*; 7 8 public class InterestCalculator extends JFrame 9 { 10 // JLabel and JTextField for principal invested 11 private JLabel principalJLabel; 12 private JTextField principalJTextField; // JLabel and JTextField for interest rate 15 private JLabel interestRateJLabel; 16 private JTextField interestRateJTextField; // JLabel and JTextField for the number of years 19 private JLabel yearsJLabel; 20 private JSpinner yearsJSpinner; // JLabel and JTextArea display amount on deposit at 23 // the end of each year up to number of years entered 24 private JLabel yearlyBalanceJLabel; 25 private JTextArea yearlyBalanceJTextArea;
2004 Prentice Hall, Inc. All rights reserved. Outline 37 InterestCalculator.ja va (2 of 7) // JScrollPane adds scrollbars to JTextArea for lengthy output 28 private JScrollPane yearlyBalanceJScrollPane; // JButton calculates amount on deposit at the 31 // end of each year up to number of years entered 32 private JButton calculateJButton; // no-argument constructor 35 public InterestCalculator() 36 { 37 createUserInterface(); 38 } // create and position GUI components; register event handlers 41 private void createUserInterface() 42 { 43 // get content pane for attaching GUI components 44 Container contentPane = getContentPane(); // enable explicit positioning of GUI components 47 contentPane.setLayout( null ); 48
2004 Prentice Hall, Inc. All rights reserved. Outline 38 InterestCalculator.ja va (3 of 7) 49 // set up principalJLabel 50 principalJLabel = new JLabel(); 51 principalJLabel.setBounds( 16, 16, 56, 24 ); 52 principalJLabel.setText( "Principal:" ); 53 contentPane.add( principalJLabel ); // set up principalJTextField 56 principalJTextField = new JTextField(); 57 principalJTextField.setBounds( 100, 16, 100, 24 ); 58 principalJTextField.setHorizontalAlignment( 59 JTextField.RIGHT ); 60 contentPane.add( principalJTextField ); // set up interestRateJLabel 63 interestRateJLabel = new JLabel(); 64 interestRateJLabel.setBounds( 16, 56, 80, 24 ); 65 interestRateJLabel.setText( "Interest rate:" ); 66 contentPane.add( interestRateJLabel ); // set up interestRateJTextField 69 interestRateJTextField = new JTextField(); 70 interestRateJTextField.setBounds( 100, 56, 100, 24 ); 71 interestRateJTextField.setHorizontalAlignment( 72 JTextField.RIGHT ); 73 contentPane.add( interestRateJTextField );
2004 Prentice Hall, Inc. All rights reserved. Outline 39 InterestCalculator.ja va (4 of 7) // set up yearsJLabel 76 yearsJLabel = new JLabel(); 77 yearsJLabel.setBounds( 16, 96, 48, 24 ); 78 yearsJLabel.setText( "Years:" ); 79 contentPane.add( yearsJLabel ); // set up yearsJSpinner 82 yearsJSpinner = new JSpinner( 83 new SpinnerNumberModel( 1, 1, 10, 1 ) ); 84 yearsJSpinner.setBounds( 100, 96, 100, 24 ); 85 contentPane.add( yearsJSpinner ); // set up yearlyBalanceJLabel 88 yearlyBalanceJLabel = new JLabel(); 89 yearlyBalanceJLabel.setBounds( 16, 136, 150, 24 ); 90 yearlyBalanceJLabel.setText( "Yearly account balance:" ); 91 contentPane.add( yearlyBalanceJLabel ); // set up yearlyBalanceJTextArea 94 yearlyBalanceJTextArea = new JTextArea(); 95 yearlyBalanceJTextArea.setEditable( false ); 96 Setting the range of your JSpinner Customizing the bounds property of yearsJSpinner Setting yearlyBalanceJTextArea ’s editable property to false
2004 Prentice Hall, Inc. All rights reserved. Outline 40 InterestCalculator.ja va (5 of 7) 97 // set up yearlyBalanceJScrollPane 98 yearlyBalanceJScrollPane = new JScrollPane( 99 yearlyBalanceJTextArea ); 100 yearlyBalanceJScrollPane.setBounds( 16, 160, 300, 92 ); 101 contentPane.add( yearlyBalanceJScrollPane ); // set up calculateJButton 104 calculateJButton = new JButton(); 105 calculateJButton.setBounds( 216, 16, 100, 24 ); 106 calculateJButton.setText( "Calculate" ); 107 contentPane.add( calculateJButton ); 108 calculateJButton.addActionListener( new ActionListener() // anonymous inner class 111 { 112 // event handler called when calculateJButton is clicked 113 public void actionPerformed( ActionEvent event ) 114 { 115 calculateJButtonActionPerformed( event ); 116 } } // end anonymous inner class ); // end call to addActionListener 121 Adding a JTextArea to a JScrollPane and setting the bounds of the JScrollPane
2004 Prentice Hall, Inc. All rights reserved. Outline 41 InterestCalculator.ja va (6 of 7) // set properties of window 124 setTitle( "Interest Calculator" ); // set window title 125 setSize( 340, 296 ); // set window size 126 setVisible( true ); // display window } // end method createUserInterface // calculate and display amounts 131 private void calculateJButtonActionPerformed( ActionEvent event ) 132 { 133 // declare variables to store user input 134 String principalText = principalJTextField.getText(); 135 double principal = Double.parseDouble( principalText ); 136 String rateText = interestRateJTextField.getText(); 137 double rate = Double.parseDouble( rateText ); Integer integerObject = ( Integer ) yearsJSpinner.getValue(); 140 int year = integerObject.intValue(); yearlyBalanceJTextArea.setText( "Year\tAmount on Deposit" ); 143 DecimalFormat dollars = new DecimalFormat( "$0.00" ); 144 Retrieving user input Displaying the header for output and creating an object to format the remainder of the output
2004 Prentice Hall, Inc. All rights reserved. Outline 42 InterestCalculator.ja va (7 of 7) 145 // calculate the total value for each year 146 for ( int count = 1; count <= year; count++ ) 147 { 148 double amount = 149 principal * Math.pow( ( 1 + rate / 100 ), count ); 150 yearlyBalanceJTextArea.append( "\n" + count + "\t" dollars.format( amount ) ); } // end for } // end method calculateJButtonActionPerformed // main method 158 public static void main( String args[] ) 159 { 160 InterestCalculator application = new InterestCalculator(); 161 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // end method main } // end class InterestCalculator Using a for statement to calculate the amount on deposit and append this data to our JTextArea