Java Reference
In-Depth Information
30
// Calculate payment
monthlyPayment
double monthlyPayment = loanAmount * monthlyInterestRate / ( 1
31
32
33
34
35
- 1 / Math.pow( 1 + monthlyInterestRate, numberOfYears * 12 ));
double totalPayment = monthlyPayment * numberOfYears * 12 ;
totalPayment
// Format to keep two digits after the decimal point
preparing output
36
37
38
39
monthlyPayment = ( int )(monthlyPayment * 100 ) / 100.0 ;
totalPayment = ( int )(totalPayment * 100 ) / 100.0 ;
// Display results
40
41
42 JOptionPane.showMessageDialog( null ,
String output = "The monthly payment is $" + monthlyPayment +
"\nThe total payment is $" + totalPayment;
output
);
43 }
44 }
The showInputDialog method in lines 6-7 displays an input dialog. Enter the interest
rate as a double value and click OK to accept the input. The value is returned as a string that
is assigned to the String variable annualInterestRateString . The
Double.parseDouble (annualInterestRateString) (line 11) is used to convert the
string into a double value.
Pedagogical Note
For obtaining input you can use either JOptionPane or Scanner —whichever is
more convenient. For consistency and simplicity, the examples in this topic use
Scanner for getting input. You can easily revise the examples using JOptionPane
for getting input.
JOptionPane or Scanner ?
2.34
Why do you have to import JOptionPane but not the Math class?
Check
2.35
Point
How do you prompt the user to enter an input using a dialog box?
2.36
How do you convert a string to an integer? How do you convert a string to a
double?
K EY T ERMS
algorithm 34
assignment operator ( = )42
assignment statement
increment operator ( ++ )54
incremental development
and testing
42
37
byte type
45
int type
45
casting 56
char type 62
constant 43
data type 35
declare variables 35
decrement operator (- -)
IPO 39
literal 48
long type 45
narrowing (of types)
56
operands 46
operator 46
overflow 45
postdecrement 54
postincrement 54
predecrement 54
preincrement 54
primitive data type
54
double type
45
encoding 62
escape character
63
expression 42
final keyword
43
float type 45
floating-point number
35
35
pseudocode 34
requirements specification
identifier
40
58
 
Search WWH ::




Custom Search