2.13. Getting Input from the Console

 
[Page 46 ( continued )]

2.12. Case Studies

In the preceding sections, you learned about variables , constants, primitive data types, operators, and expressions. You are now ready to use them to write interesting programs. This section presents three examples: computing loan payments, breaking a sum of money down into smaller units, and displaying the current time.

2.12.1. Example: Computing Loan Payments

This example shows you how to write a program that computes loan payments. The loan can be a car loan, a student loan, or a home mortgage loan. The program lets the user enter the interest rate, number of years , and loan amount, and then computes the monthly payment and the total payment. It concludes by displaying the monthly and total payments.

The formula to compute the monthly payment is as follows :


You don't have to know how this formula is derived. Nonetheless, given the monthly interest rate, number of years, and loan amount, you can use it to compute the monthly payment.

Here are the steps in developing the program:

  1. Prompt the user to enter the annual interest rate, number of years, and loan amount.

  2. Obtain the monthly interest rate from the annual interest rate.


    [Page 47]
  3. Compute the monthly payment using the preceding formula.

  4. Compute the total payment, which is the monthly payment multiplied by 12 and multiplied by the number of years.

  5. Display the monthly payment and total payment in a message dialog.

In the formula, you have to compute (1 + monthlyInterestRate) number Of Yearsx12 . The pow(a, b) method in the Math class can be used to compute a b . The Math class, which comes with the Java API, is available to all Java programs. Other useful methods in the Math class will be introduced in Chapter 5, "Methods."

Listing 2.6 gives the complete program. Figure 2.3 shows a sample run of the program.

Figure 2.3. The program accepts the annual interest rate, number of years, and loan amount, then displays the monthly payment and total payment.

Listing 2.6. ComputeLoan.java
(This item is displayed on pages 47 - 48 in the print version)
 1   import   javax.swing.JOptionPane; 2 3   public class   ComputeLoan { 4  /** Main method */  5   public static void   main(String[] args) { 6  // Enter yearly interest rate  7 String annualInterestRateString = JOptionPane.showInputDialog( 8   "Enter yearly interest rate, for example 8.25:"   ); 9 10  // Convert string to double  11   double   annualInterestRate = 12 Double.parseDouble(annualInterestRateString); 13 14  // Obtain monthly interest rate  15   double   monthlyInterestRate = annualInterestRate /   1200   ; 16 17  // Enter number of years  18 String numberOfYearsString = JOptionPane.showInputDialog( 19   "Enter number of years as an integer, \nfor example 5:"   ); 20 21  // Convert string to int  22   int   numberOfYears = Integer.parseInt(numberOfYearsString); 23 24  // Enter loan amount  25 String loanString = JOptionPane.showInputDialog( 26   "Enter loan amount, for example 120000.95:"   ); 27 

[Page 48]
 28  // Convert string to double  29   double   loanAmount = Double.parseDouble(loanString); 30 31  // Calculate payment  32    double   monthlyPayment = loanAmount * monthlyInterestRate / (   1    33  “ 1 / Math.pow(1 + monthlyInterestRate, numberOfYears *   12   ));  34    double   totalPayment = monthlyPayment * numberOfYears *   12   ;  35 36  // Format to keep two digits after the decimal point  37  monthlyPayment = (   int   )(monthlyPayment *   100   ) /   100.0   ;  38  totalPayment = (   int   )(totalPayment *   100   ) /   100.0   ;  39 40  // Display results  41  String output =   "The monthly payment is "   + monthlyPayment +  42    "\nThe total payment is "   + totalPayment;  43 JOptionPane.showMessageDialog(   null   ,  output  ); 44 } 45 } 

The showInputDialog method in lines 7 “8 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 12) is used to convert the string into a double value. If you entered an input other than a numeric value, a runtime error would occur. In Chapter 17, "Exceptions and Assertions," you will learn how to handle the exception so that the program can continue to run.

Each new variable in a method must be declared once and only once. Choose the most appropriate data type for the variable. For example, numberOfYears is best declared as an int (line 22), although it could be declared as a long , float , or double . Note that byte might be the most appropriate for numberOfYears . For simplicity, however, the examples in this book 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 32 “33.

The statements in lines 37 “38 are for formatting the number to keep two digits after the decimal point. For example, if monthlyPayment is 2076.0252175 , (int)(monthlyPayment * 100) is 207602 . Therefore, (int)(monthlyPayment * 100) / 100.0 yields 2076.02 .

The strings are concatenated into output in lines 11 “25. The linefeed escape character '\n' is in the string to display the text after '\n' in the next line.

Note

If you click Cancel in the input dialog box, no string is returned. A runtime error would occur.


2.12.2. Example: Counting Monetary Units

This section presents a program that classifies a given amount of money into smaller monetary units. The program lets the user enter an amount as a double value representing a total in dollars and cents , and outputs a report listing the monetary equivalent in dollars, quarters , dimes, nickels, and pennies, as shown in Figure 2.4.

Figure 2.4. The program receives an amount in decimals and breaks it into dollars, quarters, dimes, nickels, and pennies.
(This item is displayed on page 49 in the print version)

Your program should report the maximum number of dollars, then the maximum number of quarters, and so on, in this order.

Here are the steps in developing the program:

  1. Prompt the user to enter the amount as a decimal number such as 11.56 .

  2. Convert the amount (e.g., 11.56 ) into cents ( 1156 ).


    [Page 49]
  3. Divide the cents by 100 to find the number of dollars. Obtain the remaining cents using the cents remainder 100 .

  4. Divide the remaining cents by 25 to find the number of quarters. Obtain the remaining cents using the remaining cents remainder 25 .

  5. Divide the remaining cents by 10 to find the number of dimes. Obtain the remaining cents using the remaining cents remainder 10 .

  6. Divide the remaining cents by 5 to find the number of nickels. Obtain the remaining cents using the remaining cents remainder 5 .

  7. The remaining cents are the pennies.

  8. Display the result.

The complete program is given in Listing 2.7.

Listing 2.7. ComputeChange.java
(This item is displayed on pages 49 - 50 in the print version)
 1   import   javax.swing.JOptionPane; 2 3   public class   ComputeChange { 4  /** Main method */  5   public static void   main(String[] args) { 6  // Receive the amount  7 String amountString = JOptionPane.showInputDialog( 8   "Enter an amount in double, for example 11.56"   ); 9 10  // Convert string to double  11   double   amount = Double.parseDouble(amountString); 12 13  int remainingAmount = (int)(amount *   100   );  14 15  // Find the number of one dollars  16  int numberOfOneDollars = remainingAmount /   100   ;  17  remainingAmount = remainingAmount %   100   ;  18 19  // Find the number of quarters in the remaining amount  20   int   numberOfQuarters = remainingAmount /   25   ; 21 remainingAmount = remainingAmount %   25   ; 22 23  // Find the number of dimes in the remaining amount  24   int   numberOfDimes = remainingAmount /   10   ; 25 remainingAmount = remainingAmount %   10   ; 26 

[Page 50]
 27  // Find the number of nickels in the remaining amount  28   int   numberOfNickels = remainingAmount /   5   ; 29 remainingAmount = remainingAmount %   5   ; 30 31  // Find the number of pennies in the remaining amount  32   int   numberOfPennies = remainingAmount; 33 34  // Display results  35 String output =   "Your amount "   + amount +   " consists of \n"   + 36 numberOfOneDollars +   " dollars\n"   + 37 numberOfQuarters +   " quarters\n"   + 38 numberOfDimes +   " dimes\n"   + 39 numberOfNickels +   " nickels\n"   + 40 numberOfPennies +   " pennies"   ; 41 JOptionPane.showMessageDialog(   null   ,  output  ); 42 } 43 } 

The variable amount stores the amount entered from the input dialog box (lines 7 “11). This variable is not changed because the amount has to be used at the end of the program to display the results. The program introduces the variable remainingAmount (line 13) to store the changing remainingAmount .

The variable amount is a double decimal representing dollars and cents. It is converted to an int variable remainingAmount , which represents all the cents. For instance, if amount is 11.56 , then the initial remainingAmount is 1156 . The division operator yields the integer part of the division. So 1156 / 100 is 11 . The remainder operator obtains the remainder of the division. So 1156 % 100 is 56 .

The program extracts the maximum number of singles from the total amount and obtains the remaining amount in the variable remainingAmount (lines 16 “17). It then extracts the maximum number of quarters from remainingAmount and obtains a new remainingAmount (lines 20 “21). Continuing the same process, the program finds the maximum number of dimes, nickels, and pennies in the remaining amount.

One serious problem with this example is the possible loss of precision when casting a double amount to an int remainingAmount . This could lead to an inaccurate result. If you try to enter the amount 10.03 , 10.03 * 100 becomes 1002.9999999999999 . You will find that the program displays 10 dollars and 2 pennies. To fix the problem, enter the amount as an integer value representing cents (see Exercise 2.10).

As shown in Figure 2.4, dimes, 1 nickels, and 1 pennies are displayed in the result. It would be better not to display dimes, and to display 1 nickel and 1 penny using the singular forms of the words. You will learn how to use selection statements to modify this program in the next chapter (see Exercise 3.7).

2.12.3. Example: Displaying the Current Time

This section presents a program that displays the current time in GMT (Greenwich Mean Time) in the format hour :minute:second, such as 13:19:8 , as shown in Figure 2.5.

Figure 2.5. The program displays the current GMT.


The currentTimeMillis method in the System class returns the current time in milliseconds elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.6. This time is known as the Unix epoch because 1970 was the year when the Unix operating system was formally introduced.


[Page 51]
Figure 2.6. The System.currentTimeMillis() returns the number of milliseconds since the Unix epoch.

You can use this method to obtain the current time, and then compute the current second, minute, and hour as follows.

  1. Obtain the total milliseconds since midnight, Jan 1, 1970 in totalMilliseconds by invoking System.currentTimeMillis() (e.g., 1103203148368 milliseconds).

  2. Obtain the total seconds totalSeconds by dividing totalMilliseconds by 1000 (e.g., 1103203148368 milliseconds / 1000 = 1103203148 seconds).

  3. Compute the current second from totalSeconds % 60 (e.g., 1103203148 seconds % 60 = 8, which is the current second).

  4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 (e.g., 1103203148 seconds / 60 = 18386719 minutes).

  5. Compute the current minute from totalMinutes % 60 (e.g., 18386719 minutes % 60 = 19, which is the current minute).

  6. Obtain the total hours totalHours by dividing totalMinutes by 60 (e.g., 18386719 minutes / 60 = 306445 hours).

  7. Compute the current hour from totalHours % 24 (e.g., 306445 hours % 24 = 19, which is the current hour).

The program follows, and the output is shown in Figure 2.5.

Listing 2.8. ShowCurrentTime.java
(This item is displayed on pages 51 - 52 in the print version)
 1   import   javax.swing.JOptionPane; 2 3   public class   ShowCurrentTime { 4   public static void   main(String[] args) { 5  // Obtain the total milliseconds since the midnight, Jan 1, 1970  6   long   totalMilliseconds =  System.currentTimeMillis()  ; 7 8  // Obtain the total seconds since the midnight, Jan 1, 1970  9    long   totalSeconds = totalMilliseconds /   1000   ;  10 11  // Compute the current second in the minute in the hour  12    int   currentSecond = (   int   )(totalSeconds %   60   );  13 14  // Obtain the total minutes  15    long   totalMinutes = totalSeconds /   60   ;  16 17  // Compute the current minute in the hour  18   int   currentMinute = (   int   )(totalMinutes %   60   ); 19 20  // Obtain the total hours  21   long   totalHours = totalMinutes /   60   ; 22 

[Page 52]
 23  // Compute the current hour  24   int   currentHour = (   int   )(totalHours %   24   ); 25 26  // Display results  27  String output =   "Current time is "   + currentHour +   ":"    28  + currentMinute +   ":"   + currentSecond +   " GMT"   ;  29 30 JOptionPane.showMessageDialog(   null   ,  output  ); 31 } 32 } 

When System.currentTimeMillis() (line 6) is invoked, it returns the difference, measured in milliseconds, between the current GMT and midnight, January 1, 1970 GMT. This method returns the milliseconds as a long value.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net