Java Reference
In-Depth Information
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8
9 // Enter annual interest rate
10 System.out.print(
11
"Enter annual interest rate, for example, 8.25: " );
12
double annualInterestRate = input.nextDouble();
13
14 // Enter number of years
15 System.out.print( "Enter number of years as an integer: " );
16
int numberOfYears = input.nextInt();
17
18 // Enter loan amount
19 System.out.print( "Enter loan amount, for example, 120000.95: " );
20
double loanAmount = input.nextDouble();
21
22 // Create a Loan object
23 Loan loan =
24
new Loan(annualInterestRate, numberOfYears, loanAmount)
;
create Loan object
25
26 // Display loan date, monthly payment, and total payment
27 System.out.printf( "The loan was created on %s\n" +
28 "The monthly payment is %.2f\nThe total payment is %.2f\n" ,
29 loan.getLoanDate().toString(), loan.getMonthlyPayment(),
30 loan.getTotalPayment());
31 }
32 }
invoke instance method
invoke instance method
Enter annual interest rate, for example, 8.25:
Enter number of years as an integer:
Enter loan amount, for example, 120000.95:
The loan was created on Sat Jun 16 21:12:50 EDT 2012
The monthly payment is 17.75
The total payment is 1064.84
2.5
5
1000
The main method reads the interest rate, the payment period (in years), and the loan amount;
creates a Loan object; and then obtains the monthly payment (line 29) and the total payment
(line 30) using the instance methods in the Loan class.
The Loan class can be implemented as in Listing 10.2.
L ISTING 10.2 Loan.java
1 public
class Loan
{
2
private double annualInterestRate;
3
private int numberOfYears;
4
private double loanAmount;
5
private java.util.Date loanDate;
6
7
/** Default constructor */
8
public Loan() {
no-arg constructor
9
this ( 2 . 5 , 1 , 1000 );
10 }
11
12
/** Construct a loan with specified annual interest rate,
13
number of years, and loan amount
14
*/
 
 
Search WWH ::




Custom Search