Know Your Standards

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

You've been hired by a bank to rewrite some financial software. The program is supposed to determine the interest rate on a $15,000 car loan. The interest rate depends on the term of the loan, based on the following conditions:
36 months: 7.5%
48 months: 8%
60 months: 9%

You glance over the software and find a section of code that is badly structured.

Edit the snippet of code below without the use of any editors and/or compilers, and explain why the edit was necessary.

 int answer=0;

int months = Integer.parseInt(String input = JOptionPane.showInputDialog("How long will it" +
  " take you to pay off your loan? 36, 48, or 60 months?:"));
if(36 == months); answer = 7.5;
else if(48 == months) answer = 8;
else if(60 == months) answer = 9; 
 

If Statements and Named Constants

Wiki sign01.jpg

Solution

Start editing the code by declaring all variables and constants in the beginning of the program. This is for organization purposes, and will help to understand the code better. Providing comments on what these variables and constants contain will also be useful. Notice that the integer holding the answer is replaced with a double to handle decimals.

 double answer=0;  //This will contain the interest rate.
String input="";
int months=0;     //The String input will be converted to an int for comparison.

//Constants must be declared, ensuring that all names follow the proper naming standards.
final int SHORTEST_TIME = 36;
final int AVERAGE_TIME = 48;
final int LONGEST_TIME = 60;
final double SMALLEST_RATE = 7.5;
final double REGULAR_RATE = 8.0;
final double HIGHEST_RATE = 9.0; 

Every instruction will be clearer if each were executed in one line. It will be easier to spot any mistakes. Indentation is also necessary when breaking up this code to follow programming standards. The semi colon was deleted in the original code and will generate a syntax error if compiled. Braces are also good programming practice, in case more instructions need to be added within the condition.

 input = JOptionPane.showInputDialog("How long will it take you to pay off your loan? 36, 48, or 60 months?:");
months = Integer.parseInt(input);

if(SHORTEST_TIME == months)
{
    answer = SMALLEST_RATE;
}
else if(AVERAGE_TIME == months)
{
    answer = REGULAR_RATE;
}
else if(LONGEST_TIME == months)
{
    answer = HIGHEST_RATE;
} 
else
{
   System.out.println("Error: Invalid Output");
} 

Code

Solution Code

Back to the Program-A-Day homepage