๐ป Unit 1 Project: Digital Receipt
Overview & Setup
๐๏ธ Whenever we shop or dine out, we often spend money and receive a receipt in return. This receipt serves as proof of our purchase. The businessโs register uses specialized software that prints the receipt in a specific format, containing certain predetermined details.
๐ฅ PROJECT SETUP & SUBMISSION INSTRUCTIONS
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository - Specify the repository name:
CS2-Digital-Receipt - Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositoriessection of GitHub! - Now on your repository, click and select the
Codespacestab - Click
Create Codespace on mainand wait for the environment to load, then youโre ready to code! - ๐ Write code in this Codespace during class.
PART A: Basic Receipt
You will start with a basic receipt that you might get after making a purchase from the high school snack bar. In a later activity you will create a more complex version that includes asking the user for information (input) about items purchased so that a custom receipt can be produced for that purchase.
- Copy and paste (or retype) the following starter code into your
Main.javafile:public class Main { public static void main(String [] args) { // RECEIPT PRINTOUT SECTION System.out.println("**************************************"); System.out.println("* *"); System.out.println("* High School Snack Bar *"); System.out.println("* *"); System.out.println("* Drink ..........$1.50 *"); System.out.println("* Candy ..........$1.25 *"); System.out.println("* Hot Dog ........$2.75 *"); System.out.println("* Hamburger ......$3.50 *"); System.out.println("* *"); System.out.println("**************************************"); } } - Run the program.
- If any errors occur, fix them so the program compiles and runs successfully.
๐ก HINTS:
-
A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
-
A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
-
A run-time error is a mistake in the program that occurs during the execution of a program and typically causes the program to terminate abnormally.
-
An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the programโs execution.
PART B: Enhanced Receipt
The receipt that was generated in Part A prints String literal values (contained in quotes) for each of the items, but that is not always the best practice. In this activity you will modify the code from before to include variables that will store your high schoolโs name and the prices of the items available at the snack bar.
- Move the starter code (print statements) down several lines.
- Above the starter code, but still inside the
main()method, create a variable to store yourhighSchoolName. - Initialize separate variables to store the
priceof each snack bar item.Choose the most appropriate data type for each variable!
- Replace the literal values in
System.out.printlnwith string concatenation using your new variables.Run the program and debug if needed. Make sure the receipt displays correctly with your variables before moving on!
๐ก HINTS:
-
The variable for high school name should be of type
Stringbecause it will contain letters, and the variables for the cost of a drink, candy, hot dog, and hamburger should be of typedoublebecause each of them will contain a real number value. -
The syntax for declaring a variable is
dataType variableName = initialValue ;. -
To correctly concatenate the variable name
highSchoolNamewith the literal โSnack Barโ in the print statement, the syntax should behighSchoolNameSystem.out.printIn("* " + highSchoolName + " Snack Bar *"); -
To correctly concatenate a variable name
itemNamewith a real numberitemCostin the print statement, the syntax should beSystem.out.printIn("* " + itemName + ".............$" + itemCost +" *");
PART C: Adding Randomness
In this part we are going to add some arithmetic to the program to calculate the subtotal, tax, and total for the purchase based on ordering multiples of each of the items. To determine the number ordered of each item, your program should generate a random number between 0 and 2, inclusive, which represents the number ordered of each item. Your code should also generate an order number, which is a random number between 1 and 100, inclusive.
- Declare more variables (before the printout section):
- Order number
- Number of drinks ordered
- Number of candies ordered
- Number of hot dogs ordered
- Number of hamburgers ordered
- Tax rate
- Subtotal
- Total tax
- Total
- Use
Math.random()to generate values for the following:- Assign each item a quantity between 0 and 2 (inclusive).
- Assign an order number between 1 and 100 (inclusive).
- Update the receipt printout to use the variables for:
- Order number
- Quantity, name, and cost for each item
- Total cost for the order
- Run and debug the program.
๐ก HINTS:
- The variables for tax rate, subtotal, total tax, and total should be of type
doublebecause each will contain a real number value. -
The variables for order number and the number of drinks, candies, hot dogs, and hamburgers should be of type
intbecause each will contain a whole number. -
To generate the order number, which should be a random number between 1 and 100, inclusive, the
Math.random()method should be used. The general form of generating a random number between low and high is(int)(Math.random() * (high - low + 1) + low). For the order number example, the code should be(int)(Math.random() * 100 + 1) -
If the variable
numDrinkscontains the value that is randomly generated and the variabledrinkCostcontains the value of the cost per drink, then to calculate the total cost for the drinks, you would use the expressionnumDrinks * drinkCost. -
The subtotal can be found by adding each of the item totals. The value for the tax can be found by multiplying the subtotal and tax rate. The order total can be found by adding the subtotal and the tax.
- Because of the way decimal numbers are stored, the values of a
doublevariable value will print many decimal places. One way to display only two decimal places would be to use the statement:double value = ((int)(value * 100)/100.0); - The escape sequence for adding a new line to an output is
"\n". The escape sequence for adding a tab to an output is"\t".
PART D: Interactive Receipt
In the previous part we created variables and assigned their values directly. This is a good practice when initially designing a program, but a more robust program includes getting data values from a user or another source. In this activity we will use methods from the Scanner class to receive input from the user.
- Import the
Scannerlibrary at the top of the file:import java.util.Scanner; - Construct a
Scannerobject to handle keyboard input:Scanner input = new Scanner(System.in); - Ask the user to enter:
- Number of drinks
- Number of candies
- Number of hot dogs
- Number of hamburgers
- Store these values in the appropriate variables using
input.nextLine() - Prompt the user to enter the full high school name.
- Use
Stringclass methods to create initials from the first letters of each word (e.g., โBirch Wathen Lenoxโ โ โBWLโ). - Replace the high school name on the receipt with the generated initials.
- Calculate the orderโs total cost using the userโs input values.
- Print the updated receipt.
- Run and debug the program.
๐ก HINTS:
-
The placement of the statement
import java.util.Scanner;must be before thepublic class Mainheader. -
The placement of the statement
Scanner input = new Scanner(System.in);should be after the headerpublic static void main(String[] args). -
If the variable
nameOfSchoolcontains the four-word name of the high school, the String method substring can be used to extract the first letter. This would yield the statementfirstLetter = nameOfSchool.substring(0, 1);. -
To find the position of the first space in the high schoolโs name, the String method
indexOfcan be used. This would yield the statementint position = nameOfSchool.indexOf(" ");. -
Once the position of the space is located, the String method
substringcan be used to get the remaining words. This would yield the statementremainingWords = nameOfSchool.substring(position+1);.
BONUS: Design a Receipt
If you complete Parts A-D, start a blank Java program and try this bonus activity!
- Choose a business type for your custom receipt (e.g., store, cafรฉ, personal business).
- Write down details about the business:
- What products it sells
- Information shown on the receipt (store name, location, date, item descriptions, prices, quantities, etc.)
- Decide how many items your receipt will include.
- Draw your receipt on paper to plan the layout.
- Identify all the variables needed to store your data.
- Assign data to the variables:
- Some set with literal values
- Some set from user input
- Add creativity by including extra features:
- Generate a receipt number using part of the business name plus a random number.
- Apply a random โsurpriseโ discount (1%โ10%).
- Use
StringandMathclass methods from the Java Quick Reference.
- Test the program to ensure it displays correctly and works as intended.
Acknowledgement
Content on this page is adapted from CollegeBoard.