Difference between revisions of "Cycling Speed"

From CompSciWiki
Jump to: navigation, search
m
(edited source code at the end of page)
Line 13: Line 13:
  
 
<br /><br />
 
<br /><br />
  I need you to write a program that allows customers who visit the Bicycle Forever to calculate the speed of their bicycles. One of the members of the team stumbled upon the formula to calculate cycling speed, and knowing you are just itching for an assignment, I thought of you straightaway to implement it. The program description and the formula is below:
+
  I need you to write a program that allows customers who visit the Bicycle Forever to calculate the speed of their bicycles. One of the members of the team stumbled on the formula to calculate cycling speed, and knowing you are just itching for an assignment, I thought of you straightaway to implement the formula. The program description and the formula is below:
 
</p>
 
</p>
  
Line 270: Line 270:
 
|SolutionCode=
 
|SolutionCode=
 
import javax.swing.*;
 
import javax.swing.*;
import java.util.Date;
+
import java.text.SimpleDateFormat;
 +
import java.util.Calendar;
  
 
/**
 
/**
  * calculate a check digit for ISBNs
+
  * calculate the speed of a bicycle
 
  *
 
  *
  * @author:    1010 Instructors
+
* Bicycle Forever
  * @version:    2007-September
+
  * @author:    <insert name here>
 +
  * @version:    2011-March
 
  */
 
  */
  
public class CaseStudy1_ISBN_Solution
+
public class BicycleSpeed {
{
+
     /**....................................................main<br>
     /**
+
     * PURPOSE: inputs RPM and Number of Teeth and output speed
     * PURPOSE: inputs a 9-digit ISBN, calculates the check digit and outputs a 10-digit ISBN
+
 
     */
 
     */
     public static void main (String [] args)  
+
     public static void main (String [] args) {
    {
+
  
         //variables declared here
+
        //constants
         String temp;         //temporary input string
+
        final int FRONT_TEETH = 45;
         int isbn;           //9-digit ISBN
+
        final double WHEEL_CIRCUM = (70 * Math.PI)/100.0;  //diameter of wheels is 70cm; convert to circumference in meters
         int digit;           //isolated ISBN digit
+
         int total;           //total of isbn number when each digit is multiplied by check value
+
         //variables
         int checkDigit;     //value of total%11(as per ISBN standard)
+
         String input;                       //inputorary input string
 +
         int rpm ;                           //rpms
 +
         int rearTeeth;                     //number teeth in rear gear
 +
         double mdev ;                       //= circ [m] * (frontTeeth / REAR_TEETH)
 +
         double speed;                       //= mdev * rpm (speed in meters per minute)
  
 
         //get input
 
         //get input
         temp = JOptionPane.showInputDialog
+
         input = JOptionPane.showInputDialog ("Enter rpms.");
         ("Enter the first 9 digits of a 10-digit ISBN number.");
+
         rpm = Integer.parseInt(input);
        isbn = Integer.parseInt(temp);
+
 
 +
        input = JOptionPane.showInputDialog ("Enter number of teeth on rear gear.");
 +
rearTeeth = Integer.parseInt(input);
  
 
         //confirm input
 
         //confirm input
         System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");
+
         System.out.println ("You have entered " + rpm + " rpms and " + rearTeeth + " rear teeth");
 
+
        //isolate last digit and multiply by 9
+
        digit = (isbn % 10);
+
        total = digit * 9;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 9 + " for a running total of " + total);
+
 
+
        //isolate next digit and multiply by 8
+
        digit = (isbn % 10);
+
        total = total + digit * 8;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 8 + " for a running total of " + total);
+
 
+
        //isolate next digit and multiply by 7
+
        digit = (isbn % 10);
+
        total = total + digit * 7;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 7 + " for a running total of " + total);
+
 
+
        //isolate next digit and multiply by 6
+
        digit = (isbn % 10);
+
        total = total + digit * 6;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 6 + " for a running total of " + total);
+
 
+
        //isolate next digit and multiply by 5
+
        digit = (isbn % 10);
+
        total = total + digit * 5;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 5 + " for a running total of " + total);
+
 
+
        //isolate next digit and multiply by 4
+
        digit = (isbn % 10);
+
        total = total + digit * 4;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 4 + " for a running total of " + total);
+
 
+
        //isolate next digit and multiply by 3
+
        digit = (isbn % 10);
+
        total = total + digit * 3;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 3 + " for a running total of " + total);
+
  
         //isolate next digit and multiply by 2
+
         //find meters of development
         digit = (isbn % 10);
+
         mdev = WHEEL_CIRCUM * (FRONT_TEETH / (double)  rearTeeth);
        total = total + digit * 2;
+
         System.out.println("Meters of development: " + mdev);
        isbn = isbn / 10;
+
         System.out.println (digit + " * " + 2 + " for a running total of " + total);
+
  
         //isolate next digit and multiply by 1
+
         //find speed
         digit = (isbn % 10);
+
         speed = mdev * rpm; //speed in meters per minute
         total = total + digit * 1;
+
         speed = speed * (60.0 / 1000); //speed in km per hour
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 1 + " for a running total of " + total);
+
  
         //calculate check digit
+
         //BONUS
         checkDigit = total % 11;
+
         Calendar calendar = Calendar.getInstance();
 +
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  
         //output weighted total and check digit
+
         //output
         System.out.println ("The weighted total is: " + total +
+
         System.out.println("Speed [km/hour]: " + speed);
                            "\nThe check digit is : " + checkDigit +
+
                            "\n\nThe 10-digit ISBN is: " + temp + checkDigit);
+
  
         System.out.println("\nProgrammed by COMP 1010 Instructors");
+
         System.out.println("\nProgrammed by Bicycle Forever");
         System.out.println("Date: " + new Date());
+
         System.out.println("Date: " + dateFormat.format(calendar.getTime()));
 
         System.out.println ("*** End of Processing ***");
 
         System.out.println ("*** End of Processing ***");
 +
        System.exit(0);
  
    }//end main
+
        }//end main
}//end class
+
}end class
 
|SideSectionTitle=Cycling Speed
 
|SideSectionTitle=Cycling Speed
 
|SideSection=
 
|SideSection=

Revision as of 08:20, 31 March 2011

Back to the Case Studies homepage

Problem

You are an employer on the software team of Bikers Forever, a bicycle company. The software team uses Java and the knowledge of the Java SDK to write programs for Biker Forever. You are a great COMP 1010 student so you already have an idea of writing in Java, so in breathless anticipation, you await your next assignment from the head of the software team :)

You arrive at your desk on Monday morning and open your email in-box (as usual) to see this message from the head:

Hi <insert name here>,

I need you to write a program that allows customers who visit the Bicycle Forever to calculate the speed of their bicycles. One of the members of the team stumbled on the formula to calculate cycling speed, and knowing you are just itching for an assignment, I thought of you straightaway to implement the formula. The program description and the formula is below:

Program Description

  1. The program will prompt the user to input
    • The RPM (rotations per minute) of the bicycle
    • The number of teeth in the rear gear
  2. The program will also store as constants the number of teeth in the front gear and the diameter of the bicycle wheel. Assume the number of front teeth to be 45 and the diameter to be 70cm always.

Formula

  1. Before you calculate the speed, you must first calculate the meters of development. This is the length in meters covered by each rotation of the wheel of the bicycle. Meters of development (mdev, as we'll call them) are calculated this way:
    mdev = circumference[m] * (number front teeth / number rear teeth)
    
  2. Finally, now that we have the mdev we can calculate the speed:
    speed = mdev * rpm * 60/1000
    

Output

To display your results, assuming a customer inputs 75 for RPM and 20 for rear teeth, the output will be displayed this way:

You have entered 75 RPM and 20 rear teeth.
Meters of development: 4.948008429403924
Speed [km/hour]: 22.266037932317655

Programmed by Bicycle Forever
Date: September 18, 2008
*** End of Processing ***

Thanks!, <insert name here>, I am confident you will do a great job.
The Boss

 

Cycling Speed

Wiki start01.jpg

Solution

There are nine steps to improve this messy code so it complies with the company (and coincidentally, comp 1010) coding standards:


Organize the Code

First, organized code is vital to the readability of the code. The COMP 1010 Coding Standards give the foundation required to complete the code organization task for this case study. Each of the headings below describe a specific task that helps organize the code.

Separate the Statements

The code file contains more than one statements on each line.

int digit1 = (isbn % 10);int total = digit1 * 9;isbn = isbn / 10;
int digit2 = (isbn % 10);total = total + digit2 * 8;isbn = isbn / 10;

Each of the above lines of code performs a similar function. Each line can be interpretted as a block of code. By placing each statements on a separate line and grouping the statements into appropriate code blocks, the result should look something like the following:

int digit1 = (isbn % 10);
int total = digit1 * 9;
isbn = isbn / 10;
int digit2 = (isbn % 10);
total = total + digit2 * 8;
isbn = isbn / 10;

By placing each of the statements on a separate line, the readability of the code increases dramatically.

Separate Statements into Code Blocks

Once the statements are readable, the next step would be to organize them into code blocks as stated in COMP 1010 Coding Standards. Continuing with our previous example, the functionality of the code can be broken into two distinct code blocks.

int digit1 = (isbn % 10);
int total = digit1 * 9;
isbn = isbn / 10;

int digit2 = (isbn % 10);
total = total + digit2 * 8;
isbn = isbn / 10;

Almost each line of code in the messy code file can be considered a separate code block. Take the time to read the code and understand how everything works together before deciding which statements should be grouped together.

One of the code blocks that should be added is a variable declaration code block at the beginning of the main method. Throughout the messy code, integers are declared. All of the declaration statements should be placed at the beginning of the main method to ensure the code stays organized. Going to the previous example, two declaration statements can be moved to the top as depicted below.

int digit1;
int digit2;

digit1 = (isbn % 10);
int total = digit1 * 9;
isbn = isbn / 10;

digit2 = (isbn % 10);
total = total + digit2 * 8;
isbn = isbn / 10;

Add Comments to Explain the Code

The COMP 1010 coding standards, or the Funky Books Inc. coding standards, make numerous points concerning comments in code. To be specific, statements 1, 2, 4, and 7 can be applied to the code file for this case study. All major code blocks should be identified by now. Look over each code block and briefly explain what it does in a comment. Since all declaration statements have been moved to the top of the the main method , make sure to apply coding standard 7 from the COMP 1010 Coding Standards.

Optimize the Code by Removing Unnecessary Variables

At the top of the main method, there should now be a number of variables declared. Notice that there are nine different "digit" variables which are only used once to store the same calculation.

int digit1;
int digit2;

digit1 = (isbn % 10);
int total = digit1 * 9;
isbn = isbn / 10;

digit2 = (isbn % 10);
total = total + digit2 * 8;
isbn = isbn / 10;

The code sample from above shows two of the nine digit variables. These two variables can be replaced with a single one as follows:

int digit;

digit = (isbn % 10);
int total = digit * 9;
isbn = isbn / 10;

digit = (isbn % 10);
total = total + digit * 8;
isbn = isbn / 10;

Fix the Errors in the Code

The messy code contained a total of eight different coding errors. Each error presented in this section is ordered as it appears in the code from the case study.

Error One

String temp = JOptionPane.showInputDialog("")

Technically, the above code does not break the functionality of the application as the method call still makes the input dialog appear to take input from the user. Although, from a usability standpoint the code does cause an error. The user who is running the application needs to know what to enter as input into the input dialog. Without a proper message, the user cannot be expected to know what the application is expecting as input. An example of a proper message is as follows:

temp = JOptionPane.showInputDialog("Enter the first 9 digits of a 10-digit ISBN number.");

Error Two

int isbn = Temp;

There are two problems with the above code sample. The first problem being that the variable "Temp" is of type string and not of the primitive type int. The second problem is the name of the variable "Temp". The variable was originally declared as "temp" and Java is a case sensitive language. Both programs are repaired by replacing the code with the line below.

isbn = Integer.parseInt(temp);

Error Three

isbn = isbn // 10;

An extra front slash changes the division operation into a comment which also comments out the semi-colon required at the end of every statement. Remove the extra front slash to correct the error.

isbn = isbn / 10;

Error Four

digit = (isbn % 10) 

The statement above is missing the semi-colon at the end of the line. Add the semi-colon to fix the error.

digit = (isbn % 10);

Error Five

total = total + digit + 6;

This error is known as a run time error. A run time error does not cause a compilation error, but it causes the program to produce incorrect results. In the explaination of the ISBN check digit, the sixth ISBN number should be multiplied by six, not added. This error is fixed by changing the second addition operation to a multiplication operation.

total = total + digit * 6;

Error Six

digit = (isbn / 10);

Just like error five, the above statement causes a run time error. To isolate the last digit in the ISBN number, the ISBN must have the modulus operator applied, not the division operator. The above statement is fixed by replacing the division operator with the modulus operator.

digit = (isbn % 10);

Error Seven

digit = (isbn * 10);

The above statement is almost identical to #Error Six. The multiplication operator should be replaced with the modulus operator.

digit = (isbn % 10);

Error Eight

total = total + digit - 1;

The error in the code above is error five almost identical to #Error Five. Replace the subtraction operator with the multiplication operator to remedy this error.

total = total + digit * 1;

Add Code to Output Progress Reports as the Program Executes

To add progress reports to the program, three things need to be addressed:

  • Where to place the progress reports
  • What progress should be reported
  • Adding the code to report progress

By adding code to report on the status of the application, the user and yourself know what is happening behind the scenes when the program is executing. For a small application like this case study it may seem trivial. It is a good practice to get into as in larger programs consisting of many files each with many methods, it can be difficult to locate a run-time error in your code if the program does not explicitly say what it is currently doing.

Location

By now the code file should be broken up into multiple code blocks, as done earlier in this solution. Each code block should represent a major code segment in the program. Each code block can be considered a potential point for a progress report. Read over the code and decide which are vital points in the execution of the program.

Report Content

The next step is to decide what should be outputted to describe the progress of the program. This output can be the current value of a variable, an output statement saying that the program has reached a certain point in the code, or potentially a combination of both. A progress report should output data on the program that is relevant to its execution. For this case study, each calculation performed on the ISBN is vital to determining the check digit, therefore a progress report should output the value of each calculation.

Adding Output Code

The best way to add output to the program is by adding System.out statements to the appropriate code blocks. When adding the code, make sure the message that will be outputted is unique in comparison to the other progress report statements. Each statement should be unique as they are meant to identify the section of code being executed. If the statements are not unique, then there will be no way of telling which progress report has been outputted. Here is an example of the code before adding a System.out statement.

//isolate last digit and multiply by 9
digit = (isbn % 10);
total = digit * 9;
isbn = isbn / 10;

After the output statement is added, the code will look like the following:

//isolate last digit and multiply by 9
digit = (isbn % 10);
total = digit * 9;
isbn = isbn / 10;
System.out.println (digit + " * " + 9 + " for a running total of " + total);

When the program is executing, the following output will appear in the progress window. The ISBN number used as input for the example below is 1-2345-6789.

9 * 9 for a running total of 81

Now the you will know what part of the code is being executed along with the status of the current calculation.

Remember that this is not the only "correct" progress report. There can be many different progress reports based on how the vital points of the program were interpreted. Although, in this case study the calculations are exceptionally important points to the correct execution of the program.

Code

Solution Code

Back to the Case Studies homepage