Java Reference
In-Depth Information
2.19.2 Using Input Dialog Boxes
Having learned how to read input from an input dialog box, you can rewrite the program in
Listing 2.8, ComputeLoan.java, to read from input dialog boxes rather than from the console.
Listing 2.11 gives the complete program. Figure 2.5 shows a sample run of the program.
(a)
(b)
(c)
(d)
F
IGURE
2.5
The program accepts the annual interest rate (a), number of years (b), and loan
amount (c), then displays the monthly payment and total payment (d).
L
ISTING
2.11
ComputeLoanUsingInputDialog.java
1
import
javax.swing.JOptionPane;
2
3
public class
ComputeLoanUsingInputDialog {
4
public static void
main(String[] args) {
5
// Enter annual interest rate
6 String annualInterestRateString = JOptionPane.showInputDialog(
7
enter interest rate
"Enter annual interest rate, for example, 8.25:"
);
8
9
// Convert string to double
10
double
annualInterestRate =
11 Double.parseDouble(annualInterestRateString);
12
13
convert string to double
// Obtain monthly interest rate
14
double
monthlyInterestRate = annualInterestRate /
1200
;
15
16
// Enter number of years
17 String numberOfYearsString = JOptionPane.showInputDialog(
18
"Enter number of years as an integer, for example, 5:"
);
19
20
// Convert string to int
21
int
numberOfYears = Integer.parseInt(numberOfYearsString);
22
23
// Enter loan amount
24 String loanString = JOptionPane.showInputDialog(
25
"Enter loan amount, for example, 120000.95:"
);
26
27
// Convert string to double
28
double
loanAmount = Double.parseDouble(loanString);
29