Difference between revisions of "Cash Receipt"

From CompSciWiki
Jump to: navigation, search
Line 44: Line 44:
  
 
|Solution=
 
|Solution=
There are 12 steps to solving this problem:
+
There are some mental pre-steps you need to take before you start writing code. After, you need to set up your variables you know you need (part zero), then code the problem in two more parts (part one and part two).
  
  
 
==Break the problem down==
 
==Break the problem down==
While this problem is a bit more lengthy than others, the first rule of computer science is to break the program into pieces. Ultimately we want to get the whole program done, but we need to break it into parts we can work on and do it bit by bit. This means reading the problem and figuring out what you need to do logically step by step.
+
While this problem is a bit more lengthy than others, the first rule of Computer Science is to break the program into pieces. Ultimately we want to get the whole program done, but we need to break it into parts we can work on and do it bit by bit. This means reading the problem and figuring out what you need to do logically step by step.
  
 
==Declare your variables==
 
==Declare your variables==
Based on the problem description, we know we will need to use constants and use JOptionPane. JOptionPane means storing text in strings. We're also dealing with integers and decimal value numbers (doubles).
+
Based on the problem description, we know we will need to use constants and use [http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html JOptionPane]. [http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html JOptionPane] means storing text in [http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html 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 ([http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Double.html doubles]).
  
 
==Keep your code organized==
 
==Keep your code organized==
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]]. You need to make sure your code is properly indented, variable names are properly named and comments are included in your 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. You need to make sure your code is properly indented, variable names are properly named and initialized to zero or empty string constants which are "", and comments are included in your code.
  
 
==Get it done==
 
==Get it done==
 
Some programs will take longer than one sitting to get done. You must realize and accept that some programs can be done quickly, and some take a very long time, and that no matter what you code, you will always have to deal with bugs. Start on the programs early enough and don't procrastinate.
 
Some programs will take longer than one sitting to get done. You must realize and accept that some programs can be done quickly, and some take a very long time, and that no matter what you code, you will always have to deal with bugs. Start on the programs early enough and don't procrastinate.
  
==Look it over==
+
==Part zero, starting out==
After your program is working, check for efficiency. This will come into play later on in the degree, but you should practice doing it now. Below are some methods to help you become more efficient.
+
You will need to have two string variables. You also need three integer variables, six double variables and four double constants.
  
==Optimize the Code by Removing Unnecessary Variables==
+
'''The String variables are to:<br>'''
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]]
+
Handle all input strings<br>
declared. Notice that there are nine different "digit" [[Variables and Literals#Variables|variables]] which are only used once to store the same calculation.
+
Store the cashier's name
  
<pre>
+
'''The integer variables are to store the number of ______ bought:<br>'''
int digit1;
+
Brushes<br>
int digit2;
+
Paint sets<br>
 +
Primer<br>
  
digit1 = (isbn % 10);
+
'''The double variables are to store:<br>'''
int total = digit1 * 9;
+
The tax<br>
isbn = isbn / 10;
+
The sub total of the bill<br>
 +
The total of the bill (with tax)<br>
 +
The total payment given<br>
 +
The total change returned<br>
 +
The total change given to the nearest nickel
  
digit2 = (isbn % 10);
+
'''The double constant variables are to store:'''
total = total + digit2 * 8;
+
The tax rate<br>
isbn = isbn / 10;
+
The cost of the brushes<br>
</pre>
+
The cost of the paint<br>
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:
+
The cost of the primer
<pre>
+
int digit;
+
  
digit = (isbn % 10);
+
==Part one, continue with some code==
int total = digit * 9;
+
Now that you've completed the first task of setting up variables (and remembering to initialize them all to either 0 or empty string constants which are ""), the next task you want to do is prompt the user to enter their name. To do this, you need to use [http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html JOptionPane]. Then you want to store the text entered in a string. This can be simply done by:
isbn = isbn / 10;
+
 
+
digit = (isbn % 10);
+
total = total + digit * 8;
+
isbn = isbn / 10;
+
</pre>
+
 
+
==Fix the Errors in the Code==
+
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|cash receipt]].
+
===Error One===
+
 
<pre>
 
<pre>
String temp = JOptionPane.showInputDialog("")
+
StringVariable = 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>
 
</pre>
  
===Error Two===
+
After, you want to 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 you want to convert the entered value to an integer. This can be done using
<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>
 
<pre>
isbn = Integer.parseInt(temp);
+
IntegerVariable = Integer.parseInt(StringVariable);
 
</pre>
 
</pre>
  
===Error Three===
+
We can also assume that the user is entering a number and therefore we do not need to do any error checking.
<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===
+
'''Note for extended development:''' to error check this code, you can take the input text and store it into a string. Then you can use a piece of code called a [http://www.exampledepot.com/egs/Java%20Language/TryCatch.html try catch block].
<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 these inputs are entered, you 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 out in order per line the Cashier's name, the number of brushes bought, the number of paint cans bought, the number of primer bought, the subtotal, the tax, the total amount.
<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===
+
==Part two==
<pre>
+
Now the cashier is waiting for you to pay. Assuming you're not a thief, you will hand the cashier an amount greater than or equal to the total amount owing. Again you do not need to error check to make sure you give the cashier a proper amount.
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===
+
'''Note for extended development:''' You can check to make sure that the amount of change you give to the cashier is greater than the total owing by using an [http://download.oracle.com/javase/tutorial/java/nutsandbolts/if.html if statement].
<pre>
+
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===
+
Again 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 it to a double (no error checking again is needed, however once again you can use a [http://www.exampledepot.com/egs/Java%20Language/TryCatch.html try catch block] for further development). To convert to a double, you can use:
 
<pre>
 
<pre>
total = total + digit - 1;
+
DOubleVariable = Double.parseDouble(StringVariable);
</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>
 
</pre>
  
==Add Code to Output Progress Reports as the Program Executes==
+
Print out the money recieved, then subtract the total owed from the amount of change given. Then calculate any change the cashier needs to give back to the customer and print it out (even if it is $0.00). Finally round the amount of change given back to the nearest nickel and print that value.
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===
+
Your code is now complete!
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===
+
==Look it over==
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.
+
After your program is working, check for efficiency. This will come into play later on in the degree, but you should practice doing it now. Below are some methods to help you become more efficient.
  
===Adding Output Code===
+
==Fix the Errors in the Code==
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.
+
If you have any bugs in your program, check them over and fix them!
<pre>
+
 
//isolate last digit and multiply by 9
+
==Optimize the Code by Removing Unnecessary Variables==
digit = (isbn % 10);
+
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 extra than what the above solution suggests, see if you can get rid of any extras you don't need.
total = digit * 9;
+
 
isbn = isbn / 10;
+
==Parting statements==
</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.
+
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.
  
 
|SolutionCode=
 
|SolutionCode=
Line 230: Line 155:
 
     int numPrimer;      //number primer
 
     int numPrimer;      //number primer
 
     double tax;          // calculated tax [$]
 
     double tax;          // calculated tax [$]
     double productTotal;  // total from adult tickets alone [$]
+
     double productTotal;  // subtotal of the bill [$]
 
     double total;        // total bill [$]
 
     double total;        // total bill [$]
 
     double change;
 
     double change;

Revision as of 12:54, 29 March 2011

Back to the Case Studies homepage

Problem

Today your manager wants you to write a complete Java program that can be used by a cashier to generate customer receipts for her convenience store which sells only three items.

First: The three items are brush sets, paint sets and primer. 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 cashier’s name
2) the quantity of each item.

The program will calculate and output:
1) the subtotal
2) tax
3) total.

After the program calculates and prints out the receipt up to the total amount owed.
1) prompt the cashier to enter a payment amount,
2) calculate any change needed to be given back to the customer and
3) round the change given to the nearest nickel.

Calculate and output:
1) The change due (to the nearest penny)
2) The change due (to the nearest nickel)
3) the name of the cashier.

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), your output should look like:

Welcome to ArtSupply.

Cashier: Sarah

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


Your employer wants you to use proper programming practices which happen to be exactly the same as the standards in Comp 1010.

 

SideSectionTitle

SideSection goes here.

Solution

There are some mental pre-steps you need to take before you start writing code. After, you need to set up your variables you know you need (part zero), then code the problem in two more parts (part one and part two).


Break the problem down

While this problem is a bit more lengthy than others, the first rule of Computer Science is to break the program into pieces. Ultimately we want to get the whole program done, but we need to break it into parts we can work on and do it bit by bit. This means reading the problem and figuring out what you need to do logically step by step.

Declare your variables

Based on the problem description, we know we will need to use constants and use JOptionPane. JOptionPane means storing text in strings. We're also dealing with integers and decimal value numbers (doubles).

Keep your code organized

The COMP 1010 Coding Standards give the foundation required to complete the code organization task for this case study. You need to make sure your code is properly indented, variable names are properly named and initialized to zero or empty string constants which are "", and comments are included in your code.

Get it done

Some programs will take longer than one sitting to get done. You must realize and accept that some programs can be done quickly, and some take a very long time, and that no matter what you code, you will always have to deal with bugs. Start on the programs early enough and don't procrastinate.

Part zero, starting out

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 to:
Handle all input strings
Store the cashier's name

The integer variables are to store the number of ______ bought:
Brushes
Paint sets
Primer

The double variables are to store:
The tax
The sub total of the bill
The total of the bill (with tax)
The total payment given
The total change returned
The total change given to the nearest nickel

The double constant variables are to store: The tax rate
The cost of the brushes
The cost of the paint
The cost of the primer

Part one, continue with some code

Now that you've completed the first task of setting up variables (and remembering to initialize them all to either 0 or empty string constants which are ""), the next task you want to do is prompt the user to enter their name. To do this, you need to use JOptionPane. Then you want to store the text entered in a string. This can be simply done by:

StringVariable = JOptionPane.showInputDialog

After, you want to continue on by prompting the user to enter in 3 numbers using JOptionPane. Each time the user enters a number you want to convert the entered value to an integer. This can be done using

IntegerVariable = Integer.parseInt(StringVariable);

We can also assume that the user is entering a number and therefore we do not need to do any error checking.

Note for extended development: to error check this code, you can take the input text and store it into a string. Then you can use a piece of code called a try catch block.

After these inputs are entered, you 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 out in order per line the Cashier's name, the number of brushes bought, the number of paint cans bought, the number of primer bought, the subtotal, the tax, the total amount.

Part two

Now the cashier is waiting for you to pay. Assuming you're not a thief, you will hand the cashier an amount greater than or equal to the total amount owing. Again you do not need to error check to make sure you give the cashier a proper amount.

Note for extended development: You can check to make sure that the amount of change you give to the cashier is greater than the total owing by using an if statement.

Again use JOptionPane to prompt for an amount given, and then convert it to a double (no error checking again is needed, however once again you can use a try catch block for further development). To convert to a double, you can use:

DOubleVariable = Double.parseDouble(StringVariable);

Print out the money recieved, then subtract the total owed from the amount of change given. Then calculate any change the cashier needs to give back to the customer and print it out (even if it is $0.00). Finally round the amount of change given back to the nearest nickel and print that value.

Your code is now complete!

Look it over

After your program is working, check for efficiency. This will come into play later on in the degree, but you should practice doing it now. Below 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 extra than what the above solution suggests, see if you can get rid of any extras you don't need.

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.

Code

Solution Code

Back to the Case Studies homepage