Know Your Standards

From CompSciWiki
Revision as of 11:23, 8 April 2010 by EricaP (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Your sixteen year old brother comes to you for help in a programming assignment he has in school. He claims doesn't even understand his own code. His program is supposed to determine what the interest rate would be in a $15,000 car loan, depending on how long the user wants to take to pay it off. Here are the conditions:
36 months: 7.5%
48 months: 8%
60 months: 9%

You glance over his work and notice how badly structured his program is. 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 instead of an integer 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. Idendentation 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

SolutionCode goes here. Please DO NOT put your code in <pre> tags!

Back to the Program-A-Day homepage