Java Reference
In-Depth Information
24
double
payment = loan * c * Math.pow(1 + c, n) /
25 (Math.pow(1 + c, n) - 1);
26 System.out.println("payment = $" + (
int
) payment);
27 }
28 }
The following is a sample execution of the program (user input is in bold):
This program computes monthly mortgage payments.
loan amount :
275000
number of years :
30
interest rate :
6.75
payment = $1783
The first thing we do in the program is construct a
Scanner
object, which we will
use for console input. Next, we explain what the program is going to do, printing a
description to the console. This is essential for interactive programs. You don't want a
program to pause for user input until you've explained to the user what is going to
happen.
Below the
println
, you'll notice several pairs of statements like these:
System.out.print("loan amount : ");
double loan = console.nextDouble();
The first statement is called a
prompt,
a request for information from the user. We
use a
print
statement instead of a
println
so that the user will type the values on the
same line as the prompt (i.e., to the right of the prompt). The second statement calls the
nextDouble
method of the
console
object to read a value of type
double
from the
user. This value is stored in a variable called
loan
. This pattern of prompt/read state-
ments is common in interactive programs.
After prompting for values, the program computes several values. The formula for
computing monthly mortgage payments involves the loan amount, the total number
of months involved (a value we call
n
) and the monthly interest rate (a value we
call
c
). The payment formula is given by the following equation:
c
)
n
c
(1
+
payment
=
loan
c
)
n
(1
+
-
1
You will notice in the program that we use the
Math.pow
method for exponentia-
tion to translate this formula into a Java expression.
The final line of the program prints out the monthly payment. You might imagine
that we would simply say:
System.out.println("payment = $" + payment);
Search WWH ::
Custom Search