Difference between revisions of "Cash Receipt"

From CompSciWiki
Jump to: navigation, search
m (Added formatting)
m (fixed links)
 
(33 intermediate revisions by 3 users not shown)
Line 3: Line 3:
 
|ProblemName=Cash Receipt
 
|ProblemName=Cash Receipt
  
|Problem=Write a complete Java program that can be used by a cashier to generate customer receipts for an imaginary store which sells only three items. Make up the items and their costs. Use constants to store the cost of each of the three items and the tax rate.<br>
+
|Problem=You are a self-employed junior programmer. You've just started your own business and today, you've gotten your first job from a manager at a small arts and crafts store. The manager wants you to write a complete Java program that can be used by any cashier within her company to generate customer receipts for her convenience store which currently sells only three items.
Then, use JOptionPane to prompt the user to enter: 1) the cashier’s name, 2) the quantity of each item. The program will calculate and output: 1) the subtotal; 2) tax; and 3) total.<br>
+
Finally, prompt the cashier to enter the payment amount. Calculate and output: 1) the change due (to the nearest penny); 2) the change due (to the nearest nickel) and 3) the name of the cashier.<br><br>
+
<b><u>Some details:</b></u><br>
+
'''Constants:''' Store the cost of each item as a constant. Also, store the tax rate (7%) as a constant.<br>
+
'''Input:'''  Prompt the user to enter his/her name. Then use JOptionPane to input the quantity of each item.<br>
+
'''Calculate and Output:''' 1) the subtotal (the cost of the items without tax); 2) tax; and 3) total (of product plus taxes). Also output the name of your store at the top of the receipt.<br>
+
'''Use Math.round() to round all output to two decimal spots.'''<br>
+
If your input values were 2 brush sets ($8 each), 3 paint sets ($40 each), and 4 cans of primer ($18.75 each), your output should look like:
+
  
  
Welcome to ArtSupply.
+
First: The three items are brush sets, paint sets and primer. Since the prices of these materials will not change for a long time, you should use constants to store the cost of each of the three items and the tax rate.
  
Cashier: Sarah
+
Then, since the program is going to be used by multiple cashiers, use JOptionPane to prompt the user to enter:
 +
# The current cashier’s name
 +
# The quantity of each item.
  
2 brush sets at $ 8.0
 
  
3 paint sets at $ 40.0
+
The program will calculate and output:
 +
# The subtotal
 +
# Tax
 +
# Total.
  
4 primer at $ 18.75
 
  
Product Total: $211.0
+
As each item is entered, the program prints out the input given on a new line each time. After the quantity of the last item is entered, the program calculates a subtotal and prints it, then it prints out the tax value, and then calculates the subtotal plus tax as a final total and prints that value.
  
Tax: $ 14.77
+
Now the program waits for the cashier to enter in a payment given amount. So now:
 +
# Prompt the cashier to enter a payment amount,
 +
# Calculate and print any change needed to be given back to the customer (if they overpaid) and
 +
# Round the change given to the nearest nickel and print that value.
 +
# Finally print out "Change given by: <cashier's name>"
  
Total = 225.77
 
  
Expand the program to prompt the user to input the amount of payment given by the customer. Then calculate and output 1) the change (rounded to the nearest penny) and 2) the change rounded to the next highest nickel, and 2) the cashier’s name (again).
+
==Some details:==
To begin, add a comment as shown below so the marker can easily find this part of your program.
+
'''Constants:''' Store the cost of each item as a constant. Also, store the tax rate (7%) as a constant.
//2B******************************************************
+
Variables: Add any new variables to the top of the program (with the variables from 2a).
+
Input: Use JOptionPane to input payment given.
+
Calculate:  When finding the change, use Math.ceil to round up so the customer gets the full change, and possibly more. For example, if the change due is 4.637, round to 4.64 using pennies and 4.65 using nickels.
+
  
 +
'''Input:'''  Prompt the user to enter his/her name. Then use JOptionPane to input the quantity of each item. Finally use JOptionPane to input the amount of change given.
  
Output: Your output should look like:
+
'''Calculate and Output:'''
Money received: 250.0
+
# The subtotal (the cost of the items without tax)
Change due: 24.23
+
# Tax
Change rounded up to nearest nickel: 24.25
+
# Total (of product plus taxes).
Change given by: Sarah
+
 
 +
 
 +
Also output the name of your store at the top of the receipt. When finding the change, use [http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html Math.ceil] to round up so the customer gets the full change, and possibly more. For example, if the change due is 4.637, round to 4.64 using pennies and 4.65 using nickels. 
 +
 +
'''Use Math.round() to round all output to two decimal spots.'''
 +
 
 +
If your input values were 2 brush sets ($8 each), 3 paint sets ($40 each), and 4 cans of primer ($18.75 each), and your cashier's name is Joni, your output should look like:  
 +
 
 +
 
 +
Welcome to ArtSupply.
 +
 +
Cashier: Joni
 +
2 brush sets at $ 8.0
 +
3 paint sets at $ 40.0
 +
4 primer at $ 18.75
 +
Product Total: $211.0
 +
Tax: $ 14.77
 +
Total = $ 225.77
 +
Money received: $ 250.0
 +
Change due: $ 24.23
 +
Change rounded up to nearest nickel: $ 24.25
 +
Change given by: Joni
 +
 
 +
 
 +
'''The store manager wants you to use proper programming practices which happen to be exactly the same as the standards in Comp 1010.'''
  
  
  
 
|Solution=
 
|Solution=
There are nine steps to improve this messy code so it complies with the company (and coincidentally, comp 1010) coding standards:
+
Before starting to write code, we will think about the problem in greater detail. Then we will declare and initialize the needed variables. Finally, we will program the problem in two parts: handling input, and obtaining output.
  
 +
==Break the Problem Down==
 +
This problem is lengthier than others. Luckily in Computer Science, breaking the problem into pieces is often the best strategy. Ultimately the goal is to have the whole program done, and breaking the problem into parts allows it to be manageable. Start by reading the problem and planning which parts to do first.
  
==Organize the Code==
+
==Keep the Code Organized==
First, organized code is vital to the readability of the code. The [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards] give the foundation required to complete the code organization task for this [[Case_Study_I|case study]]. Each of the headings below describe a specific task that helps organize the code.
+
The [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards] give the guidelines required to keep our code organized. Make sure the code is properly indented, all variables are properly named (as in: ''double change'', as opposed to: ''double a'') and initialized. Integer variables can be initialized to zero, if no other value is more appropriate. Strings can be initialized to be empty, that is two double quotes: "". Also, include comments in your code.
  
===Separate the Statements===
+
==Get it Done==
The code file contains more than one [[Your First Java Program#Statements|statements]] on each line.
+
Some programs will take longer than one sitting to complete. Realize and accept that some programs can be done quickly, and others take more time. An inevitable part of programming is dealing with bugs. Start on programs early enough and do not procrastinate. Leaving a program to the last minute &mdash; especially further on in the Computer Science degree &mdash; will cost you.
<pre>
+
int digit1 = (isbn % 10);int total = digit1 * 9;isbn = isbn / 10;
+
int digit2 = (isbn % 10);total = total + digit2 * 8;isbn = isbn / 10;
+
</pre>
+
Each of the above lines of code performs a similar function. Each line can be interpretted as a block of code. By placing each [[Your First Java Program#Statements|statements]] on a separate line and grouping the statements into appropriate code blocks, the result should look something like the following:
+
<pre>
+
int digit1 = (isbn % 10);
+
int total = digit1 * 9;
+
isbn = isbn / 10;
+
int digit2 = (isbn % 10);
+
total = total + digit2 * 8;
+
isbn = isbn / 10;
+
</pre>
+
By placing each of the [[Your First Java Program#Statements|statements]] on a separate line, the readability of the code increases dramatically.  
+
  
===Separate Statements into Code Blocks===
+
=Part One: Declare Variables and Constants=
Once the [[Your First Java Program#Statements|statements]] are readable, the next step would be to organize them into code blocks as stated in [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards]. Continuing with our previous example, the functionality of the code can be broken into two distinct code blocks.
+
<pre>
+
int digit1 = (isbn % 10);
+
int total = digit1 * 9;
+
isbn = isbn / 10;
+
  
int digit2 = (isbn % 10);
+
Based on the problem description, we know we will need to use constants, variables, and [[Input_using_JOptionPane| JOptionPane]]. JOptionPane requires that we store text in strings, so we must use [[Strings| strings]]. We're also dealing with [http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html integers] and decimal value numbers. We will store the decimal value numbers as ([http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Double.html doubles]).
total = total + digit2 * 8;
+
isbn = isbn / 10;
+
</pre>
+
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 [[Your First Java Program#Statements|statements]] should be grouped together.
+
  
One of the code blocks that should be added is a variable declaration code block at the beginning of [[Your First Java Program#The Main Method|the main method]]. Throughout the [[Case Study I#Code|messy code]], integers are declared. All of the [[Variables and Literals#Variables|declaration statements]] should be placed at the beginning of [[Your First Java Program#The Main Method|the main method]] to ensure the code stays organized. Going to the previous example, two [[Variables and Literals#Variables|declaration statements]] can be moved to the top as depicted below.
+
You will need to have two string variables. You also need three integer variables, six double variables and four double constants.
<pre>
+
int digit1;
+
int digit2;
+
  
digit1 = (isbn % 10);
+
'''The string variables are for:'''
int total = digit1 * 9;
+
* temporarily storing input strings for quantity
isbn = isbn / 10;
+
* storing the cashier's name
  
digit2 = (isbn % 10);
+
'''The integer variables are to store the quantity of items bought. You will need one integer variable for each of the following :'''
total = total + digit2 * 8;
+
* Brushes
isbn = isbn / 10;
+
* Paint sets
</pre>
+
* Primer
  
===Add Comments to Explain the Code===
+
'''The double variables are for storing:'''
The [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 coding standards], or the Funky Books Inc. coding standards, make numerous points concerning [[Comments|comments]] in code. To be specific, statements 1, 2, 4, and 7 can be applied to the code file for this [[Case Study I|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 [[Variables and Literals#Variables|declaration statements]] have been moved to the top of the [[Your First Java Program#The Main Method|the main method]] , make sure to apply coding standard 7 from the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards].
+
* The tax
 +
* The subtotal of the bill
 +
* The total of the bill (this includes tax)
 +
* The total payment given
 +
* The total change returned
 +
* The total change given to the nearest nickel
  
==Optimize the Code by Removing Unnecessary Variables==
+
'''The double constants are for storing:'''
At the top of [[Your First Java Program#The Main Method|the main method]], there should now be a number of [[Variables and Literals#Variables|variables]]
+
* The tax rate
declared. Notice that there are nine different "digit" [[Variables and Literals#Variables|variables]] which are only used once to store the same calculation.
+
* The cost of the brushes
 +
* The cost of the paint
 +
* The cost of the primer
  
<pre>
+
To declare a [[named constant]] add the keyword '''final''' before the type. For example, the following line declares a constant double called cost:
int digit1;
+
final double cost;
int digit2;
+
  
digit1 = (isbn % 10);
+
=Part Two: Handling Input=
int total = digit1 * 9;
+
Now that we have completed the first task of setting up variables, we need to program a sequence of prompts, calculations and some printing to the terminal.
isbn = isbn / 10;
+
The following pseudocode gives you a good overview of what needs to be done. Pseudocode is a great tool to start writing a program without technical details slowing us down.
  
digit2 = (isbn % 10);
+
//Pseudocode:
total = total + digit2 * 8;
+
Print out "Welcome to ArtSupply"
isbn = isbn / 10;
+
Prompt for cashier's name.
</pre>
+
Prompt for number of brush sets.
The code sample from above shows two of the nine digit [[Variables and Literals#Variables|variables]]. These two [[Variables and Literals#Variables|variables]] can be replaced with a single one as follows:
+
Prompt for number of primers.
<pre>
+
int digit;
+
Calculate product total.
 +
Print product total.
 +
 +
Calculate tax.
 +
Print tax.
 +
 +
Calculate total.
 +
Print total.
 +
 +
Prompt for money received.
 +
Print the money received.
 +
 +
Calculate change due.
 +
Print the change due.
 +
 +
Calculate change rounded up to the nearest nickel.
 +
Print change rounded up to the nearest nickel.
 +
Print cashier's name.
  
digit = (isbn % 10);
 
int total = digit * 9;
 
isbn = isbn / 10;
 
  
digit = (isbn % 10);
+
To prompt for input, use the JOptionPane class. To understand how to use the JOptionPane for input, read [Input_using_JOptionPane Input Using JOptionPane]. In order to get input, use JOptionPane's showInputDialog method. This method returns the text the user typed into the input dialog box as a string. Store that text in a String variable. This can be simply done roughly like this:
total = total + digit * 8;
+
isbn = isbn / 10;
+
</pre>
+
  
==Fix the Errors in the Code==
+
someStringVariable = JOptionPane.showInputDialog("What is your input?");
The [[Case Study I#Code|messy code]] contained a total of eight different coding errors. Each error presented in this section is ordered as it appears in the [[Case Study I#Code|code]] from the [[Case Study I|case study]].
+
===Error One===
+
<pre>
+
String temp = JOptionPane.showInputDialog("")
+
</pre>
+
Technically, the above code does not break the functionality of the application as the method call still makes the [[Input using JOptionPane#Input Dialog|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 using JOptionPane#Input Dialog|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:
+
<pre>
+
temp = JOptionPane.showInputDialog("Enter the first 9 digits of a 10-digit ISBN number.");
+
</pre>
+
  
===Error Two===
+
Once we have the input text stored, we want to print out the string value and move the cursor to a new line. We can do this by using the System.out.println("<text>") function. Continue on by prompting the user to enter in 3 numbers using [http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html JOptionPane]. Each time the user enters a number we want to convert the entered value to an integer and print the number. The following code illustrates how to convert the entered value to an integer:
<pre>
+
int isbn = Temp;
+
</pre>
+
There are two problems with the above code sample. The first problem being that the [[Variables and Literals#Variables|variable]] "Temp" is of type [[Strings|string]] and not of the primitive type [[Common Primitive Variables#Primitive Type int|int]]. The second problem is the name of the [[Variables and Literals#Variables|variable]] "Temp". The [[Variables and Literals#Variables|variable]] was originally declared as "temp" and Java is a [[Your First Java Program#Case Sensitivity|case sensitive]] language. Both programs are repaired by replacing the code with the line below.
+
<pre>
+
isbn = Integer.parseInt(temp);
+
</pre>
+
  
===Error Three===
+
someIntegerVariable = Integer.parseInt(StringVariable);
<pre>
+
isbn = isbn // 10;
+
</pre>
+
An extra front slash changes the [[Arithmetic Operators|division operation]] into a comment which also comments out the semi-colon required at the end of every [[Your First Java Program#Statements|statement]]. Remove the extra front slash to correct the error.
+
<pre>
+
isbn = isbn / 10;
+
</pre>
+
  
===Error Four===
+
This method parseInt works well so long as the user enters a number and not something else. This means that the user could crash the program by not entering a number when they are supposed to. The correct way to fix this potential problem is to do error checking. However, for the sake of simplicity, we will assume that the user always enters a number.
<pre>
+
digit = (isbn % 10)
+
</pre>
+
The [[Your First Java Program#Statements|statement]] above is missing the semi-colon at the end of the line. Add the semi-colon to fix the error.
+
<pre>
+
digit = (isbn % 10);
+
</pre>
+
  
===Error Five===
+
After the inputs are entered and properly stored, we need to do some math. Proceed by calculating the subtotal, tax and the total amount using simple math equations. After the values are calculated, print the subtotal, the tax, and the total amount. Make sure the output is in the same order as the output shown in the problem description.
<pre>
+
total = total + digit + 6;
+
</pre>
+
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 [[Case Study I#ISBN Check Digit Overview|ISBN check digit]], the sixth ISBN number should be multiplied by six, not added. This error is fixed by changing the second [[Arithmetic Operators|addition]] operation to a [[Arithmetic Operators|multiplication]] operation.
+
<pre>
+
total = total + digit * 6;
+
</pre>
+
  
===Error Six===
+
'''You are now about half way done this program!'''
<pre>
+
digit = (isbn / 10);
+
</pre>
+
Just like [[#Error Five|error five]], the above [[Your First Java Program#Statements|statement]] causes a run time error. To isolate the last digit in the ISBN number, the ISBN must have the [[Arithmetic Operators|modulus operator]] applied, not the [[Arithmetic Operators|division operator]]. The above statement is fixed by replacing the [[Arithmetic Operators|division operator]] with the [[Arithmetic Operators|modulus operator]].
+
<pre>
+
digit = (isbn % 10);
+
</pre>
+
  
===Error Seven===
+
=Part Three: Output=
<pre>
+
Now the cashier is waiting for the customer to pay. Assuming the customer is not a thief, they would hand the cashier an amount greater than or equal to the total amount owing. This means we do not need to error-check to make sure the customer gives the cashier a proper amount (meaning that the customer did not shortchange the cashier).
digit = (isbn * 10);
+
</pre>
+
The above [[Your First Java Program#Statements|statement]] is almost identical to [[#Error Six]]. The [[Arithmetic Operators|multiplication operator]] should be replaced with the [[Arithmetic Operators|modulus operator]].
+
<pre>
+
digit = (isbn % 10);
+
</pre>
+
  
===Error Eight===
+
Use [http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html JOptionPane] to prompt for an amount given, and then convert the string returned to a double (again assume they enter a proper number, so that no error checking is needed). The following code shows how to convert a string to a double:
<pre>
+
total = total + digit - 1;
+
</pre>
+
The error in the code above is [[#Error Five|error five]] almost identical to [[#Error Five]]. Replace the [[Arithmetic Operators|subtraction operator]] with the [[Arithmetic Operators|multiplication operator]] to remedy this error.
+
<pre>
+
total = total + digit * 1;
+
</pre>
+
  
==Add Code to Output Progress Reports as the Program Executes==
+
DoubleVariable = Double.parseDouble(StringVariable);
To add progress reports to the program, three things need to be addressed:
+
<ul>
+
<li>Where to place the progress reports</li>
+
<li>What progress should be reported</li>
+
<li>Adding the code to report progress</li>
+
</ul>
+
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 I|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 [[#Separate the Statements into Code Blocks|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===
+
Print the amount given. Calculate any change the cashier needs to give to the customer and print it (even if it is $0.00). Round the amount of change to the nearest nickel and print that value.
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 [[Variables and Literals|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 I|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===
+
'''Your code is now complete!'''
The best way to add output to the program is by adding [[Output using System.out|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 [[Your First Java Program#Statements|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 [[Output using System.out|System.out]] statement.
+
<pre>
+
//isolate last digit and multiply by 9
+
digit = (isbn % 10);
+
total = digit * 9;
+
isbn = isbn / 10;
+
</pre>
+
After the output [[Your First Java Program#Statements|statement]] is added, the code will look like the following:
+
<pre>
+
//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);
+
</pre>
+
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.
+
<pre>
+
9 * 9 for a running total of 81
+
</pre>
+
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 I|case study]] the calculations are exceptionally important points to the correct execution of the program.
+
=Post-programming Instructions=
 +
Now you may want to close your program, submit it and be happy that you're done! Unfortunately, reality doesn't work that way. You are only about half done with your program. Now you need to make sure your program works, and is up to standards. Below are a few steps you need to take when you feel you have finished your program.
 +
 
 +
==Look it over==
 +
After your program is working, check for efficiency. This will come into play later on in the Computer Science degree, but you should practice doing it now. The next two sections are some methods to help you become more efficient.
 +
 
 +
==Fix the Errors in the Code==
 +
If you have any bugs in your program, check them over and fix them!
 +
 
 +
==Optimize the Code by Removing Unnecessary Variables==
 +
At the top of [[Your First Java Program#The Main Method|the main method]], you should have a number of variables. If you have any more than what the above solution suggests, see if you can get rid of any extras you don't need.
 +
 
 +
==Try to Break your Program==
 +
In this question, breaking your code would be easy to do unless you implement the error-checking procedures. You could easily break your code by entering in a letter instead of a number and trying to convert that string into an integer or double. However, if you do implement the error checking procedures in this program, and for your future programs, the best way to make sure you have complete and fantastic code is if you cannot make your program explode no matter what you do. The number one reason individuals are penalized for their code is because a random situation arises, even though it's highly unlikely to happen (but they do), and the programmer has not added the necessary code to handle the exception.
 +
 
 +
==The Feeling of Hopelessness==
 +
There will be times that arise when you've gone too far down one path and your code is too far gone to fix properly. Understand that at times completely restarting the whole program over is a quicker and saner option than attempting to fix it properly. In other cases, backing up part way is more efficient. Make sure you save working versions of your program along the way. Lastly within this section, back up your code! If your computer dies and you lose your file, that's your responsibility!
 +
 
 +
==Parting Statements==
 +
Remember that this is not the only "correct" way to do this program. There can be many different ways to accomplish this program and it can be further developed to handle error-checking from any aspect. Remember to code efficiently, accurately, and properly. This means: no more excess code than needed, know what you're trying to code and break it down as needed to accomplish parts of it at a time rather than the whole thing in one sitting, and comment and indent your code appropriately. Always remember to test your program as much as you possibly can, and practice, practice, practice! The more you code, the better you will become at it.
  
 
|SolutionCode=
 
|SolutionCode=
 
import javax.swing.*;
 
import javax.swing.*;
import java.util.Date;
 
  
/**
+
/**....................................................................A1Q3
  * calculate a check digit for ISBNs
+
  * Print ticket invoice
  *
+
  * 74.101 SECTION L08/L09
  * @author:    1010 Instructors
+
* INSTRUCTOR  Terry Andres/Christina Penner
  * @version:    2007-September
+
* ASSIGNMENT  #1  QUESTION #2
 +
  * @author C. Penner/T. Andres, 999999
 +
  * @version 2004-Feb-09
 
  */
 
  */
 +
public class A1_Receipt {
  
public class CaseStudy1_ISBN_Solution
+
  /**..................................................................main
{
+
  * PURPOSE: main reads items for a store, prints invoice, and calculates change
    /**
+
  * @param args is a list of command line arguments
    * 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
+
    String inputString; // for all inputs
        String temp;         //temporary input string
+
    String name;
        int isbn;           //9-digit ISBN
+
        int digit;          //isolated ISBN digit
+
        int total;          //total of isbn number when each digit is multiplied by check value
+
        int checkDigit;      //value of total%11(as per ISBN standard)
+
  
        //get input
+
    int numBrush;        // number of brush sets
        temp = JOptionPane.showInputDialog
+
    int numPaint;        // number of paint sets
        ("Enter the first 9 digits of a 10-digit ISBN number.");
+
    int numPrimer;      //number primer
        isbn = Integer.parseInt(temp);
+
    double tax;          // calculated tax [$]
 +
    double productTotal;  // subtotal of the bill [$]
 +
    double total;        // total bill [$]
 +
    double change;
 +
    double pennyChange;
 +
    double payment;
  
        //confirm input
+
    final double TAX    = 0.07;  // rate; fraction of bill [-]
        System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");
+
    final double BRUSH  = 8.00;  // adult ticket price [$]
 +
    final double PAINT  = 40.00;  // children's ticket price [$]
 +
    final double PRIMER = 18.75;  // rate, adult; improvement tax [-]
  
        //isolate last digit and multiply by 9
+
    //input cashier name
        digit = (isbn % 10);
+
    name = JOptionPane.showInputDialog
        total = digit * 9;
+
    ("Enter Cashier name please");
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 9 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 8
+
    System.out.println("Welcome to ArtSupply. \nCashier: " + name);
        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
+
    //input nummber brush sets
        digit = (isbn % 10);
+
    inputString = JOptionPane.showInputDialog
        total = total + digit * 7;
+
    ("How many brush sets?");
        isbn = isbn / 10;
+
    numBrush = Integer.parseInt(inputString);
        System.out.println (digit + " * " + 7 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 6
+
    System.out.println(numBrush + " brush sets at $ " + BRUSH);
        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
+
    //input nummber paint sets
        digit = (isbn % 10);
+
    inputString = JOptionPane.showInputDialog
        total = total + digit * 5;
+
    ("How many paint sets?");
        isbn = isbn / 10;
+
    numPaint = Integer.parseInt(inputString);
        System.out.println (digit + " * " + 5 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 4
+
    System.out.println(numPaint + " paint sets at $ " + PAINT);
        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
+
    //input nummber primer
        digit = (isbn % 10);
+
    inputString = JOptionPane.showInputDialog
        total = total + digit * 3;
+
    ("How many primers?");
        isbn = isbn / 10;
+
    numPrimer= Integer.parseInt(inputString);
        System.out.println (digit + " * " + 3 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 2
+
    System.out.println(numPrimer + " primer at $ " + PRIMER);
        digit = (isbn % 10);
+
        total = total + digit * 2;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 2 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 1
+
    //calculate productTotal, levy, tax and total
        digit = (isbn % 10);
+
    //round all above values to 2 decimal spots
        total = total + digit * 1;
+
    productTotal = ((numPaint*PAINT) + (numPrimer*PRIMER) + (numBrush*BRUSH));
        isbn = isbn / 10;
+
    productTotal = Math.round (productTotal * 100) / 100.0;
        System.out.println (digit + " * " + 1 + " for a running total of " + total);
+
  
        //calculate check digit
+
    tax = TAX * ((numPaint*PAINT) + (numPrimer*PRIMER) + (numBrush*BRUSH));
        checkDigit = total % 11;
+
    tax = Math.round (tax * 100)/100.0;
  
        //output weighted total and check digit
+
    total = productTotal + tax;
        System.out.println ("The weighted total is: " + total +
+
    total = Math.round (total * 100)/100.0;
                            "\nThe check digit is : " + checkDigit +
+
                            "\n\nThe 10-digit ISBN is: " + temp + checkDigit);
+
  
        System.out.println("\nProgrammed by COMP 1010 Instructors");
+
    //output totals
        System.out.println("Date: " + new Date());
+
        System.out.println ("*** End of Processing ***");
+
  
     }//end main
+
     System.out.println ("Product Total: $" + productTotal);
}//end class
+
    System.out.println ("Tax: $ "+ tax);
|SideSectionTitle=Funky Books
+
    System.out.println ("Total = " + total);
 +
 
 +
 
 +
    //2B*****************************************************************
 +
 
 +
    //input payment
 +
    inputString = JOptionPane.showInputDialog("Enter payment amount.");
 +
    payment = Double.parseDouble(inputString);
 +
    System.out.println("Money received: " + payment);
 +
 
 +
    //calculate change to nearest nickel
 +
    change = payment - total;
 +
    pennyChange = Math.round(change*100)/100.0;
 +
 
 +
 
 +
    System.out.println("Change: " + change + "\nChange due: " + pennyChange);
 +
    System.out.println("Change rounded up to nearest nickles: " + (Math.ceil(pennyChange*20)/20.0));
 +
    System.out.println("Change given by: " + name);
 +
 
 +
 
 +
 
 +
    System.out.println("\nProgrammed by 1010 Instructors");
 +
    System.out.println ("*** End of Processing ***");
 +
 
 +
  }
 +
}
 +
 
 +
 
 +
 
 +
|SideSectionTitle=Cash
 
|SideSection=
 
|SideSection=
[[Image:Wiki_start01.jpg|center]]<BR>
+
[[Image:Money_casestudy.jpg|center]]<BR>
 +
 
 +
 
  
 
}}
 
}}

Latest revision as of 15:19, 7 April 2011

Back to the Case Studies homepage

Problem

You are a self-employed junior programmer. You've just started your own business and today, you've gotten your first job from a manager at a small arts and crafts store. The manager wants you to write a complete Java program that can be used by any cashier within her company to generate customer receipts for her convenience store which currently sells only three items.


First: The three items are brush sets, paint sets and primer. Since the prices of these materials will not change for a long time, you should use constants to store the cost of each of the three items and the tax rate.

Then, since the program is going to be used by multiple cashiers, use JOptionPane to prompt the user to enter:

  1. The current cashier’s name
  2. The quantity of each item.


The program will calculate and output:

  1. The subtotal
  2. Tax
  3. Total.


As each item is entered, the program prints out the input given on a new line each time. After the quantity of the last item is entered, the program calculates a subtotal and prints it, then it prints out the tax value, and then calculates the subtotal plus tax as a final total and prints that value.

Now the program waits for the cashier to enter in a payment given amount. So now:

  1. Prompt the cashier to enter a payment amount,
  2. Calculate and print any change needed to be given back to the customer (if they overpaid) and
  3. Round the change given to the nearest nickel and print that value.
  4. Finally print out "Change given by: <cashier's name>"


Some details:

Constants: Store the cost of each item as a constant. Also, store the tax rate (7%) as a constant.

Input: Prompt the user to enter his/her name. Then use JOptionPane to input the quantity of each item. Finally use JOptionPane to input the amount of change given.

Calculate and Output:

  1. The subtotal (the cost of the items without tax)
  2. Tax
  3. Total (of product plus taxes).


Also output the name of your store at the top of the receipt. When finding the change, use Math.ceil to round up so the customer gets the full change, and possibly more. For example, if the change due is 4.637, round to 4.64 using pennies and 4.65 using nickels.

Use Math.round() to round all output to two decimal spots.

If your input values were 2 brush sets ($8 each), 3 paint sets ($40 each), and 4 cans of primer ($18.75 each), and your cashier's name is Joni, your output should look like:


Welcome to ArtSupply.

Cashier: Joni
2 brush sets at $ 8.0
3 paint sets at $ 40.0
4 primer at $ 18.75
Product Total: $211.0
Tax: $ 14.77
Total = $ 225.77
Money received: $ 250.0
Change due: $ 24.23
Change rounded up to nearest nickel: $ 24.25
Change given by: Joni


The store manager wants you to use proper programming practices which happen to be exactly the same as the standards in Comp 1010.

 

Cash

Money casestudy.jpg

Solution

Before starting to write code, we will think about the problem in greater detail. Then we will declare and initialize the needed variables. Finally, we will program the problem in two parts: handling input, and obtaining output.

Break the Problem Down

This problem is lengthier than others. Luckily in Computer Science, breaking the problem into pieces is often the best strategy. Ultimately the goal is to have the whole program done, and breaking the problem into parts allows it to be manageable. Start by reading the problem and planning which parts to do first.

Keep the Code Organized

The COMP 1010 Coding Standards give the guidelines required to keep our code organized. Make sure the code is properly indented, all variables are properly named (as in: double change, as opposed to: double a) and initialized. Integer variables can be initialized to zero, if no other value is more appropriate. Strings can be initialized to be empty, that is two double quotes: "". Also, include comments in your code.

Get it Done

Some programs will take longer than one sitting to complete. Realize and accept that some programs can be done quickly, and others take more time. An inevitable part of programming is dealing with bugs. Start on programs early enough and do not procrastinate. Leaving a program to the last minute — especially further on in the Computer Science degree — will cost you.

Part One: Declare Variables and Constants

Based on the problem description, we know we will need to use constants, variables, and JOptionPane. JOptionPane requires that we store text in strings, so we must use strings. We're also dealing with integers and decimal value numbers. We will store the decimal value numbers as (doubles).

You will need to have two string variables. You also need three integer variables, six double variables and four double constants.

The string variables are for:

  • temporarily storing input strings for quantity
  • storing the cashier's name

The integer variables are to store the quantity of items bought. You will need one integer variable for each of the following :

  • Brushes
  • Paint sets
  • Primer

The double variables are for storing:

  • The tax
  • The subtotal of the bill
  • The total of the bill (this includes tax)
  • The total payment given
  • The total change returned
  • The total change given to the nearest nickel

The double constants are for storing:

  • The tax rate
  • The cost of the brushes
  • The cost of the paint
  • The cost of the primer

To declare a named constant add the keyword final before the type. For example, the following line declares a constant double called cost:

final double cost;

Part Two: Handling Input

Now that we have completed the first task of setting up variables, we need to program a sequence of prompts, calculations and some printing to the terminal. The following pseudocode gives you a good overview of what needs to be done. Pseudocode is a great tool to start writing a program without technical details slowing us down.

//Pseudocode:
Print out "Welcome to ArtSupply"
Prompt for cashier's name.
Prompt for number of brush sets.
Prompt for number of primers.

Calculate product total.
Print product total.

Calculate tax.
Print tax.

Calculate total.
Print total.

Prompt for money received.
Print the money received.

Calculate change due.
Print the change due.

Calculate change rounded up to the nearest nickel.
Print change rounded up to the nearest nickel.
Print cashier's name.


To prompt for input, use the JOptionPane class. To understand how to use the JOptionPane for input, read [Input_using_JOptionPane Input Using JOptionPane]. In order to get input, use JOptionPane's showInputDialog method. This method returns the text the user typed into the input dialog box as a string. Store that text in a String variable. This can be simply done roughly like this:

someStringVariable = JOptionPane.showInputDialog("What is your input?");

Once we have the input text stored, we want to print out the string value and move the cursor to a new line. We can do this by using the System.out.println("<text>") function. Continue on by prompting the user to enter in 3 numbers using JOptionPane. Each time the user enters a number we want to convert the entered value to an integer and print the number. The following code illustrates how to convert the entered value to an integer:

someIntegerVariable = Integer.parseInt(StringVariable);

This method parseInt works well so long as the user enters a number and not something else. This means that the user could crash the program by not entering a number when they are supposed to. The correct way to fix this potential problem is to do error checking. However, for the sake of simplicity, we will assume that the user always enters a number.

After the inputs are entered and properly stored, we need to do some math. Proceed by calculating the subtotal, tax and the total amount using simple math equations. After the values are calculated, print the subtotal, the tax, and the total amount. Make sure the output is in the same order as the output shown in the problem description.

You are now about half way done this program!

Part Three: Output

Now the cashier is waiting for the customer to pay. Assuming the customer is not a thief, they would hand the cashier an amount greater than or equal to the total amount owing. This means we do not need to error-check to make sure the customer gives the cashier a proper amount (meaning that the customer did not shortchange the cashier).

Use JOptionPane to prompt for an amount given, and then convert the string returned to a double (again assume they enter a proper number, so that no error checking is needed). The following code shows how to convert a string to a double:

DoubleVariable = Double.parseDouble(StringVariable);


Print the amount given. Calculate any change the cashier needs to give to the customer and print it (even if it is $0.00). Round the amount of change to the nearest nickel and print that value.

Your code is now complete!

Post-programming Instructions

Now you may want to close your program, submit it and be happy that you're done! Unfortunately, reality doesn't work that way. You are only about half done with your program. Now you need to make sure your program works, and is up to standards. Below are a few steps you need to take when you feel you have finished your program.

Look it over

After your program is working, check for efficiency. This will come into play later on in the Computer Science degree, but you should practice doing it now. The next two sections are some methods to help you become more efficient.

Fix the Errors in the Code

If you have any bugs in your program, check them over and fix them!

Optimize the Code by Removing Unnecessary Variables

At the top of the main method, you should have a number of variables. If you have any more than what the above solution suggests, see if you can get rid of any extras you don't need.

Try to Break your Program

In this question, breaking your code would be easy to do unless you implement the error-checking procedures. You could easily break your code by entering in a letter instead of a number and trying to convert that string into an integer or double. However, if you do implement the error checking procedures in this program, and for your future programs, the best way to make sure you have complete and fantastic code is if you cannot make your program explode no matter what you do. The number one reason individuals are penalized for their code is because a random situation arises, even though it's highly unlikely to happen (but they do), and the programmer has not added the necessary code to handle the exception.

The Feeling of Hopelessness

There will be times that arise when you've gone too far down one path and your code is too far gone to fix properly. Understand that at times completely restarting the whole program over is a quicker and saner option than attempting to fix it properly. In other cases, backing up part way is more efficient. Make sure you save working versions of your program along the way. Lastly within this section, back up your code! If your computer dies and you lose your file, that's your responsibility!

Parting Statements

Remember that this is not the only "correct" way to do this program. There can be many different ways to accomplish this program and it can be further developed to handle error-checking from any aspect. Remember to code efficiently, accurately, and properly. This means: no more excess code than needed, know what you're trying to code and break it down as needed to accomplish parts of it at a time rather than the whole thing in one sitting, and comment and indent your code appropriately. Always remember to test your program as much as you possibly can, and practice, practice, practice! The more you code, the better you will become at it.

Code

Solution Code

Back to the Case Studies homepage