Java Reference
In-Depth Information
30 System.out.println( "The monthly payment is $" +
31 ( int )(monthlyPayment * 100 ) / 100.0 );
32 System.out.println( "The total payment is $" +
33 ( int )(totalPayment * 100 ) / 100.0 );
34 }
35 }
casting
casting
Enter annual interest rate, e.g., 5.75%:
Enter number of years as an integer, e.g., 5:
Enter loan amount, e.g., 120000.95:
The monthly payment is $2076.02
The total payment is $373684.53
5.75
15
250000
line#
10
13
18
22
25
27
variables
annualInterestRate
5.75
monthlyInterestRate
0.0047916666666
numberOfYears
15
loanAmount
250000
monthlyPayment
2076.0252175
totalPayment
373684.539
Line 10 reads the annual interest rate, which is converted into the monthly interest rate
in line 13.
Choose the most appropriate data type for the variable. For example, numberOfYears
is best declared as an int (line 18), although it could be declared as a long , float , or
double . Note that byte might be the most appropriate for numberOfYears . For simplic-
ity, however, the examples in this topic will use int for integer and double for floating-
point values.
The formula for computing the monthly payment is translated into Java code in lines 25-27.
Casting is used in lines 31 and 33 to obtain a new monthlyPayment and totalPayment
with two digits after the decimal points.
The program uses the Scanner class, imported in line 1. The program also uses the Math
class, and you might be wondering why that class isn't imported into the program. The Math
class is in the java.lang package, and all classes in the java.lang package are implicitly
imported. Therefore, you don't need to explicitly import the Math class.
java.lang package
Stage 5: Testing
After the program is implemented, test it with some sample input data and verify whether the
output is correct. Some of the problems may involve many cases, as you will see in later chap-
ters. For these types of problems, you need to design test data that cover all cases.
Tip
The system design phase in this example identified several steps. It is a good approach
to developing and testing these steps incrementally by adding them one at a time. This
approach makes it much easier to pinpoint problems and debug the program.
incremental development and
testing
 
 
Search WWH ::




Custom Search