๐Ÿ’ป 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
  1. Go to the public template repository for our class: BWL-CS Java Template
  2. Click the button above the list of files then select Create a new repository
  3. Specify the repository name: CS2-Digital-Receipt
  4. Click

    Now you have your own personal copy of this starter code that you can always access under the Your repositories section of GitHub!

  5. Now on your repository, click and select the Codespaces tab
  6. Click Create Codespace on main and wait for the environment to load, then youโ€™re ready to code!
  7. ๐Ÿ“ 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.

  1. Copy and paste (or retype) the following starter code into your Main.java file:
      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("**************************************");
      }
      }
    
  2. Run the program.
  3. 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.

  1. Move the starter code (print statements) down several lines.
  2. Above the starter code, but still inside the main() method, create a variable to store your highSchoolName.
  3. Initialize separate variables to store the price of each snack bar item.

    Choose the most appropriate data type for each variable!

  4. Replace the literal values in System.out.println with 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 String because it will contain letters, and the variables for the cost of a drink, candy, hot dog, and hamburger should be of type double because 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 highSchoolName with the literal โ€œSnack Barโ€ in the print statement, the syntax should be highSchoolNameSystem.out.printIn("* " + highSchoolName + " Snack Bar *");

  • To correctly concatenate a variable name itemName with a real number itemCost in the print statement, the syntax should be System.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.

  1. 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
  2. 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).
  3. Update the receipt printout to use the variables for:
    • Order number
    • Quantity, name, and cost for each item
    • Total cost for the order
  4. Run and debug the program.


๐Ÿ’ก HINTS:
  • The variables for tax rate, subtotal, total tax, and total should be of type double because 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 int because 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 numDrinks contains the value that is randomly generated and the variable drinkCost contains the value of the cost per drink, then to calculate the total cost for the drinks, you would use the expression numDrinks * 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 double variable 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.

  1. Import the Scanner library at the top of the file:
    import java.util.Scanner;
    
  2. Construct a Scanner object to handle keyboard input:
    Scanner input = new Scanner(System.in);
    
  3. Ask the user to enter:
    • Number of drinks
    • Number of candies
    • Number of hot dogs
    • Number of hamburgers
  4. Store these values in the appropriate variables using input.nextLine()
  5. Prompt the user to enter the full high school name.
  6. Use String class methods to create initials from the first letters of each word (e.g., โ€œBirch Wathen Lenoxโ€ โ†’ โ€œBWLโ€).
  7. Replace the high school name on the receipt with the generated initials.
  8. Calculate the orderโ€™s total cost using the userโ€™s input values.
  9. Print the updated receipt.
  10. Run and debug the program.


๐Ÿ’ก HINTS:
  • The placement of the statement import java.util.Scanner; must be before the public class Main header.

  • The placement of the statement Scanner input = new Scanner(System.in); should be after the header public static void main(String[] args).

  • If the variable nameOfSchool contains the four-word name of the high school, the String method substring can be used to extract the first letter. This would yield the statement firstLetter = nameOfSchool.substring(0, 1);.

  • To find the position of the first space in the high schoolโ€™s name, the String method indexOf can be used. This would yield the statement int position = nameOfSchool.indexOf(" ");.

  • Once the position of the space is located, the String method substring can be used to get the remaining words. This would yield the statement remainingWords = nameOfSchool.substring(position+1);.


BONUS: Design a Receipt

If you complete Parts A-D, start a blank Java program and try this bonus activity!

  1. Choose a business type for your custom receipt (e.g., store, cafรฉ, personal business).
  2. Write down details about the business:
    • What products it sells
    • Information shown on the receipt (store name, location, date, item descriptions, prices, quantities, etc.)
  3. Decide how many items your receipt will include.
  4. Draw your receipt on paper to plan the layout.
  5. Identify all the variables needed to store your data.
  6. Assign data to the variables:
    • Some set with literal values
    • Some set from user input
  7. 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 String and Math class methods from the Java Quick Reference.
  8. Test the program to ensure it displays correctly and works as intended.



Acknowledgement

Content on this page is adapted from CollegeBoard.