Академический Документы
Профессиональный Документы
Культура Документы
Last Revision: June, 2001 ( McCann ) Students always seem to have trouble understanding (or maybe just doing) what I expect of them when I assign a program. The requirements are really very straight-forward; it's mostly a matter of leaving yourself plenty of time to get everything done. To help you understand what's expected of you, in this document I'll take a simple sample programming assignment and guide you through the major steps in the program development process. (If you are looking for details on program documentation, you will find some here but you really should visit my Programming Style page, which has my collection of style documents, including a few style pages from other people. Most of it is developed with experienced programmers in mind. This document is meant for students who are just starting to learn Java.)
(McCann)
Fat (grams)
Total Calories
66
21
480
Hand In: On the due date, turn in the following items: A printout of your documented Java program, and a printout of the output your program produced when run on each of the sets of data given above. Be sure to write your name in the upper right hand corner of the printout; this will make it easier for you to reclaim your program when I return it to you.
This is pretty typical of my program handouts. Things to notice: The due date, given at the top. You are required to submit your completed, documented program to me within the first 5 minutes of class on that date. After 5 minutes, the program will be considered late. No whining, please. You are an adult; take responsibility for your actions, or lack of action, as the case may be.
The system requirement. Sometimes I'll insist that you do the assignment in the lab using Linux and BlueJ; sometimes I'll accept programs that are done on a PC with a Java system such as the JDK, Visual J++, or JBuilder. Why can't you do all of your programs on your PC? Because you should learn how to use computer systems other than PCs. Our lab systems run Linux, which is a popular free version of UNIX; being familiar with UNIX is a good thing, especially in this department. You are here to learn, aren't you? The overview section will usually tell you what task is facing you. The assignment section will say what your program is to do about solving that task. The data section will tell you what data to use to test your program. Please realize that the given data is what I want you to use to generate the printed output that you will turn in. You are STRONGLY ENCOURAGED to create your own test data, too. My data just helps me see if your program is working correctly; even if your program produces the correct output on my data, it may still have problems. Finally, the last section tells you what to hand in on the due date. Sometimes I'll include other sections, such as a sample output section or a hints section.
In this case, you need to write a program that gets two pieces of input, computes a percentage, and outputs all three pieces of information. This is obviously very simple, and the first program or two of the semester will be about as simple as this one. After that, they'll get more complex, so that you can start using more features of the language.
3. The program's operational requirements: Which language system you used, special compilation information, where the input can be located on disk, etc. 4. Required features of the assignment that you were not able to include, and/or information about bugs that are still known to exist. (Be honest and complete!) To help you, I've created a template that you can import into your program that contains a label for each section that I want to see. All you have to do is fill in the blanks; I can't make it much easier than that. The Block Comment Templates with Examples page shows the External Documentation template, and you can find it in the directory /home/student/Classes/mccann/general/templates from the lab machines as well. You might wish to make copies of the templates in your home directory, just to make it easy to use your editor's file import command (:r in the vi editor, for example) to drop it into your program; importing the template can save a lot of typing. Here's what the external documentation template ( external.txt) looks like:
/ *====================================================================== ======= | Assignment: Program #[n] | Author: [Your Name (Your E-mail Address)] | | Course: [Course Number (Course Name), Semester and Year] | Instructor: L. McCann | Sect. Leader: [Your Section Leader's name] | Due Date: [Due Date], at the beginning of class | | Language: [Program Language (Development Environment)] | Packages: [Names and Sources of any special code libraries used] | Compile/Run: [How to Compile and Run this program] | +---------------------------------------------------------------------------| | Description: [Describe the program's goal, IN DETAIL.] | | Input: [Describe the sources and formats of all user-supplied | input required by the program.] | | Output: [Describe the output that the user should expect the | program to produce.] | | Techniques: [Names of standard algorithms employed, explanations
| of why things were done they way they were done, etc. | This is the place for technical information that another | programmer would like to know.] | | Required Features Not Included: | [If the assignment specifies a feature that you were | unable to include in the program, mention that omission | here. Otherwise, state that you were able to include | all of the required features in your program.] | | Known Bugs: [If you know of any problems with the code, provide | details here, otherwise clearly state that you know | of know logic errors.] | *====================================================================== =====*/
Note that I've included some brief comments with each section, to let you know what you need to add. Because deleting all of those comments is a pain, I've got a comment-free version in the same directory called ext.txt that you can import instead. You should be able to fill out all of this template except for the last two sections before you write the program. Here's what it might look like for our example assignment:
/ *====================================================================== ======= | Assignment: Program # -1 | Author: Keyser Soze (keyser@onestepahead.net) | | Course: CSCI 241 (Computer Science I) | Instructor: L. McCann | Sect. Leader: Wee Lufdaleeder | Due Date: Smarch 36, 2038, at the beginning of class | | Language: Java (JDK 1.3, BlueJ 1.1.0) | Packages: java.io | Compile/Run: BlueJ: Compile: Create a project; add this class to | it; click 'Compile' | Run: Right-click class icon; select | 'void main(args)'; click 'OK' | JDK: Compile: javac Calories.java | Run: java Calories | +----------------------------------------------------------------------------
| Description: This program determines what percentage of the calories | in a food product are due to the food's fat content. | | The user is asked to input the number of grams of fat in one | serving of the food, and the total calories in one serving. | A gram of fat contains 9 calories, so the percentage of | the food's calories that are due to fat is found by using | this formula: | | # of grams of fat * 9 | percentage = ----------------------------- * 100 | calories in a serving | | Input: The user is required to enter the grams of fat in one | serving of the food in question, and the total number of | calories in that one serving. It is expected that the | user will type these two pieces of information at his or | her keyboard. | | Output: The program will display an explanation of its purpose, | will prompt the user for the input, and will display the | percentage of the food's calories that are due to fat. All | output is displayed on the user's screen. | | Techniques: The program's steps are as follows: | | 1. The program displays its purpose | 2. The user is prompted to enter the grams of fat | and calories per serving | 3. The percentage of calories due to fat is | computed | 4. The percentage is displayed to the user, along | with the given input information. | | No particular algorithms are used. The Java IO package | is accessed to perform console I/O and thus avoid use | of a third-party I/O package. | | Required Features Not Included: All required features are included. | | Known Bugs: None; the program operates correctly. |
*====================================================================== =====*/
Please pay attention to the amount of information; the explanations are all quite detailed. Many students try to include a bare minimum of information in their documentation; that's not good at all. The documentation should help the reader understand the program, not raise more questions than it answers. This example shows an adequate amount of information. (Can you think of some additional information that you'd like to see included?) Some students think that the reader can just refer to the assignment handout to get the information. Remember two things: First, the documentation is part of the program code; the handout isn't. Second, when you get a job as a programmer, your boss is not going to go around giving you assignment handouts. You might as well get in the habit of writing good, informative documentation now. Naturally, the programmer will need to revisit the documentation after the program is complete and verify that all of the information is correct (and fill in the final two sections). But, if you do a good job of planning the details of the program in advance, you won't have to change much, if anything.
public class Calories { public static void main (String[] args) { BufferedReader keyboard; // input stream int gramsOfFat = 0, // number of grams of fat in one serving totalCalories = 0; // number of calories in one serving
from fat
double percent = 0;
keyboard = new BufferedReader(new InputStreamReader(System.in)); try { gramsOfFat = Integer.parseInt(keyboard.readLine()); } catch (IOException e) {} try { totalCalories = Integer.parseInt(keyboard.readLine()); } catch (IOException e) {} System.out.println(gramsOfFat + " " + totalCalories + " " + percent); } }
Yes, this is very spartan. Don't worry, we'll fill in the details in due time. The point is, we can compile and run this program as-is, and be convinced that we are able to successfully read and write the data. It doesn't make much sense to write the percentage calculations until we know that the calculations will have the correct values to work with. By including a simple output statement, we can see that the values are being read correctly. If you were to compile and run this program under Linux using the Sun JDK, here's what you'd see:
$ javac Calories.java $ java Calories 3 170 3 170 0.0
Obviously, we'll need to make these input and output actions a lot more "user friendly" before we finish. Next, we can add the calculations:
import java.io.*; methods // For access to console I/O classes and
public class Calories { public static final double CALORIES_PER_GRAM = 9.0; fat colories public static void main (String[] args)
// a gram of // has 9
{ serving
// input stream // number of grams of fat in one // number of calories in one serving // fraction of calories due to fat // percentage of total calories
from fat
keyboard = new BufferedReader(new InputStreamReader(System.in)); try { gramsOfFat = Integer.parseInt(keyboard.readLine()); } catch (IOException e) {} try { totalCalories = Integer.parseInt(keyboard.readLine()); } catch (IOException e) {} fatFraction = (gramsOfFat * CALORIES_PER_GRAM) / totalCalories; percent = fatFraction * 100; System.out.println(gramsOfFat + " " + totalCalories + " " + percent); } }
Don't forget to test the calculations to ensure that they are working correctly. Remember the example calculation given in the assignment handout? It makes for a good test case:
$ javac Calories.java $ java Calories 3 170 3 170 15.88235294117647
Eventually, you'll have added all of the functionality that is required of your program, will have tested its operation thoroughly, and will have added any remaining documentation. At this point, you may choose to add some "extras" that enhance the program but were not required by the assignment. (I never have problems when you do more than the assignment requires!) Here's what the completed program might look like:
/ *====================================================================== ======= | Assignment: Program # -1 | Author: Keyser Soze (keyser@onestepahead.net) | | Course: CSCI 241 (Computer Science I)
L. McCann Wee Lufdaleeder Smarch 36, 2038, at the beginning of class Java (JDK 1.3, BlueJ 1.1.0) java.io BlueJ: Compile: Create a project; add this class to it; click 'Compile' Run: Right-click class icon; select 'void main(args)'; click 'OK' JDK: Compile: javac Calories.java Run: java Calories
+---------------------------------------------------------------------------| Description: This program determines what percentage of the calories | in a food product are due to the food's fat content. | | The user is asked to input the number of grams of fat in one | serving of the food, and the total calories in one serving. | A gram of fat contains 9 calories, so the percentage of | the food's calories that are due to fat is found by using | this formula: | | # of grams of fat * 9 | percentage = ----------------------------- * 100 | calories in a serving | | Input: The user is required to enter the grams of fat in one | serving of the food in question, and the total number of | calories in that one serving. It is expected that the | user will type these two pieces of information at his or | her keyboard. | | Output: The program will display an explanation of its purpose, | will prompt the user for the input, and will display the | percentage of the food's calories that are due to fat. All | output is displayed on the user's screen. | | Techniques: The program's steps are as follows: | | 1. The program displays its purpose | 2. The user is prompted to enter the grams of fat | and calories per serving | 3. The percentage of calories due to fat is
| computed | 4. The percentage is displayed to the user, along | with the given input information. | | No particular algorithms are used. The Java IO package | is accessed to perform console I/O and thus avoid use | of a third-party I/O package. | | Required Features Not Included: All required features are included. | | Known Bugs: None; the program operates correctly. | *====================================================================== =====*/ import java.io.*; methods // For access to console I/O classes and
public class Calories { public static final double CALORIES_PER_GRAM = 9.0; fat colories
// a gram of // has 9
public static void main (String[] args) { BufferedReader keyboard; // input stream int gramsOfFat = 0, // number of grams of fat in one serving totalCalories = 0; // number of calories in one serving double fatFraction, // fraction of calories due to fat percent; // percentage of total calories from fat System.out.print("This program will tell you what percentage " + "of the calories in a serving\n" + "of a food are from the food's fat content.\n\n"); /* * Read input from the keyboard */ keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.print("How many grams of fat are in one serving? try { gramsOfFat = Integer.parseInt(keyboard.readLine()); } catch (IOException e) {} ");
");
System.out.print("How many total calories are in one serving? try { totalCalories = Integer.parseInt(keyboard.readLine()); } catch (IOException e) {} /* * Compute the percent of calories due to fat */ fatFraction = (gramsOfFat * CALORIES_PER_GRAM) / totalCalories; percent = fatFraction * 100; /* * Pretty-print the input and results to the screen. */ if (gramsOfFat == 1) { System.out.print("\nA food with 1 gram of fat "); } else { System.out.print("\nA food with " + gramsOfFat + " grams of } if (totalCalories == 1) { System.out.print("and 1 calorie per serving\n"); } else { System.out.print("and " + totalCalories + " calories per serving\n"); } System.out.print("has " + twoPlaces(percent) + "% of those calories from fat.\n");
fat ");
-----
/*--------------------------------------------------- twoPlaces | | | | | | | | Method twoPlaces (Calories) Purpose: By default, Java will display floating point values to a large number of decimal places. This method rounds the value to two decimal places, which makes the value easier to read when displayed. Pre-condition: A floating point value of the form *.def*
has '*'
| | | | | | | | |
been supplied, where a letter represents one digit and represents 0 or more digits. Post-condition: The given floating point value is returned in the form *.dg, with g=e if f < 5, or g=e+1 if f >= 5. Parameters: number (IN) -- the floating point value to be modified
Returns:
*-------------------------------------------------------------------*/ public static double twoPlaces (double number) { double shiftRight, // number with . moved two places to the right rounded, // shiftRight w/o extraneous digits shiftLeft; // rounded with decimal point restored shiftRight = number * 100; rounded = Math.round(shiftRight); shiftLeft = rounded / 100; return shiftLeft; } }
In this program, I decided that it would be nice if the output wording matched the values the user entered. The IF-ELSE statements will make the words match the quantity; for example, "1 gram" instead of "1 grams". This step wasn't required, but it does make for a more polished final program. The twoPlaces method helps clean up the output by reducing the number of digits shown after the decimal point. And here's what the user will see when s/he runs it:
$ javac Calories.java $ java Calories This program will tell you what percentage of the calories in a serving of a food are from the food's fat content. How many grams of fat are in one serving? 3 How many total calories are in one serving? 170 A food with 3 grams of fat and 170 calories per serving has 15.88% of those calories from fat.
3. Is my documentation complete? (Did I finish the external documentation? Are my variable names meaningful? Are the variable declarations documented? Did I use white space effectively? Did I include an internal block comment for each method?) 4. Did I run my program on all of the provided test data (if any)? 5. Did I create my own test cases and verify my program's correctness on them? 6. Did I check the results by hand to ensure that the program's logic is correct? 7. Have I printed out everything that I need to turn in? 8. Did I electronically submit my program according to the instructor's directions? If everything looks good, then you're ready to hand it in. Want to learn more about good programming style? Please visit my Programming Style Documents page for pointers to additional documents about programming style. Do you have a comment on this page? I'd like to hear it; you can email me at mccannl@acm.org.