CS 001 -- Computer Science I
(McCann)
Program # -1: Calories Due to Fat
Due Date: Smarch 36th, 2028, at the beginning of class
Overview: Any dietician will tell you that limiting your daily fat intake to be under 30% of your total calories is a good idea. But how many of the calories in your favorite foods are from fat? Nutrition labels will tell you how many grams of fat are in a serving, and how many total calories are in that serving, but you need to do the rest of the figuring on your own.
As it happens, a gram of fat has about 9 calories. Therefore, if you take the grams of fat in a serving of a particular food, multiply it by 9 and divide by the total calories in the serving, you'll get the fraction of the calories due to fat. To get the result as a percentage, just multiply by 100.
For example, consider a product that has 3 grams of fat and 170 calories per serving. There are 27 calories due to fat (3 * 9), and 27 / 170 = 0.1588. Multiplying by 100 gives the final answer: 15.88 percent of the calories are due to fat.
Assignment: Write a complete, well-documented Java program that begins by asking the user to enter the grams of fat and the calories in a serving of a food product. The program will compute the percentage of the food's calories that are due to fat, and will display the input information and the percentage in the form of a complete English sentence.
Data: Run your program twice, once for each set of data shown in the following table:
Fat (grams) |
Total Calories |
|
1 |
1 |
66 |
2 |
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.
/*============================================================================= | 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.
/*============================================================================= | Assignment: Program # -1 | Author: Keyser Soze (keyser@onestepahead.net) | | Course: CS 001 (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.
import java.io.*; // For access to console I/O classes and methods 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 double percent = 0; // 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) {} 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.
$ javac Calories.java $ java Calories 3 170 3 170 0.0Obviously, we'll need to make these input and output actions a lot more "user friendly" before we finish.
import java.io.*; // For access to console I/O classes and methods public class Calories { public static final double CALORIES_PER_GRAM = 9.0; // a gram of fat // has 9 colories 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 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.88235294117647Eventually, 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: CS 001 (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. | *===========================================================================*/ import java.io.*; // For access to console I/O classes and methods public class Calories { public static final double CALORIES_PER_GRAM = 9.0; // a gram of fat // has 9 colories 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 fat "); } 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"); } /*--------------------------------------------------- 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: number rounded to two decimal places *-------------------------------------------------------------------*/ 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.
$ 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.