Unit 2B Projects

From CS Awesome 2CC BY-NC-SA 4.0Original page

Java2 class periods2 exercises20 graded tests

Files

README.mdDownload

Unit 2B Projects

Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.

These projects were created by Leigh Anne Fitz and Lisa Ferran to provide engaging, standards-aligned learning experiences for AP Computer Science A students. The autograding tests were designed by Kate McDonnell.

Now that your programs can make decisions, it's time to make them repeat those decisions efficiently. In these projects, you'll explore how loops allow programs to execute instructions multiple times without writing the same code over and over. You'll use iteration to solve problems, process data, and build algorithms that are both efficient and easy to maintain.

Each project is designed to reinforce these concepts through authentic programming tasks. As you complete them, focus on recognizing patterns, choosing the appropriate type of loop, and tracing your algorithms to ensure they repeat the correct number of times. Great programmers know that well-designed loops make programs more powerful, flexible, and efficient.

Review: Using for Loops to Repeat Code

A for loop is used when you know how many times you want a section of code to repeat. The loop uses a counter variable that keeps track of the number of repetitions. The general structure of a for loop is:

for (initialization; condition; update) {
    // code that repeats
}

Example: Loop 5 times and print a message each time:

for (int i = 0; i < 5; i++) {
    System.out.println("Hello!");
}

How it works:

  • int i = 0 creates the counter and starts it at 0.
  • i < 5 keeps the loop running while i is less than 5.
  • i++ increases the counter by 1 after each repetition.

The loop above runs when i is 0, 1, 2, 3, and 4 - a total of 5 times.

Check your understanding: The variable num stores the number of times a loop should repeat. Which for loop header correctly repeats a block of code num times? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/unit2b-projects.html#unit2b-project1-choose1

Unit 2B Project 1 - Grades

Exercise 1

Write a program that allows the user to input the number of grades he or she wants to be averaged. Then use a for loop structure to have the user input all the test grades individually, calculating the sum of these grades as they are being entered. These amounts, including the sum, are to be all ints. After all the grades have been entered, the program will calculate the average (what data type should this variable be?). Print out the average for the number of grades entered.

Open the 01-unit2b-project1-grades folder and edit Grades.java. Press Run to try it; Run Tests checks it (10 tests). Run feeds it the input in input.txt; change that file to try other input.

Review: Using while Loops

A while loop repeats a section of code as long as a condition is true. While loops are useful when you do not know exactly how many times a loop will repeat.

A sentinel value is a special value that tells a program when to stop repeating. The sentinel value is not usually processed as regular data.

Example: Continue entering names until the user enters "Q":

String name = input.nextLine();

while (!name.equals("Q"))
{
  System.out.println("Hello " + name);
  name = input.nextLine();
}

The loop continues until the user enters the sentinel value "Q".

Check your understanding: Which condition should be used to continue a loop that asks the user for numbers until they enter -1? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/unit2b-projects.html#unit2b-project2-choose1

A validation loop repeatedly asks for input until the user provides an acceptable value. This helps prevent invalid data from entering a program.

Example: Require a number between 1 and 100:

int score = input.nextInt();

while (score < 1 || score > 100)
{
  System.out.println("Invalid score. Try again.");
  score = input.nextInt();
}

The loop continues while the input is invalid and stops when the input is acceptable.

Check your understanding: A program requires the user to enter a positive number. Which loop correctly validates the input? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/unit2b-projects.html#unit2b-project2-choose2

The String.format() method can be used to display a double value with a specific number of decimal places. To format a number to two decimal places, use: String.format("%.02f", number)

  • %f indicates that the value is a floating-point number (double).
  • .02 specifies that exactly two digits should appear after the decimal point.

Example:

double price = 12.5;

System.out.println(String.format("%.02f", price));

// Output:  12.50

The original value is not changed; String.format() only controls how the value is displayed.

Unit 2B Project 2 - Concert Tickets (Loop)

Recall the Concert Tickets program from Unit 2A where the user chooses a seat based on the location with the costs listed below (remember that these values should be used as ints).

Seat location     Concert ticket price ($)
B (box)           $75
P (pavillion)     $30
L (lawn)          $21

This will be a similar situation where the user will enter an upper or lowercase B, P, or L to choose a seat. Include the following:

  • Allow the user to continue buying tickets (one at a time). At the end of the loop, ask the user if they would like to purchase another ticket. Y for yes, and N for No.
  • When prompting the user for a ticket type, if the user inputs an invalid type, use a loop to prompt the user to keep entering a seat type until a valid input is received. This is to be done with a while data verification loop.
  • Keep a running total of the number of each type of ticket purchased and the subtotals for the costs of each type of ticket (these will need to be stored as ints)
  • Calculate a convenience fee of $1.50 per ticket (this will need to be a double).
  • Calculate the total cost of all tickets, including the convenience fee (this will need to be a double).

After all tickets have been purchased, display the quantity and type of each ticket bought with a subtotal, the total convenience fee, and a total price for all the tickets.

Example output:

2   box tickets         $150
4   pavillion tickets   $120
1   lawn tickets        $21
    Convenience fee     $10.50
    Total               $301.50

*Be sure to put a $ in front of all monetary amounts, and be sure to use String formatting on the convenience fee and total so that you will ensure two decimal places.

Exercise 2

Modify and expand the Unit 2A Concert Tickets program to process multiple ticket orders iteratively. Implement a loop allowing the user to purchase tickets one at a time until they choose to stop, enforce input validation for seat selections using a while loop, track counts and subtotals for each ticket type, apply a per-ticket convenience fee, and present an itemized final receipt with properly formatted currency values.

Please refer to the detailed requirements above for specific pricing, variable types, and formatting guidelines when writing your solution.

Open the 02-unit2b-project2-concert-tickets-loop folder and edit ConcertTickets.java. Press Run to try it; Run Tests checks it (10 tests). Run feeds it the input in input.txt; change that file to try other input.

For teachers

Unit 2B Projects

Students read CSAwesome2's “Unit 2B Projects” in CS Room and work through its 2 Java coding exercises.

  • Time: 2 class periods
  • Tests: 20 in 2 graded exercises, set up for you when you import the lesson

Goals

  • Practice for Unit 2: Selection and Iteration.

Before class

In class

  1. Students read README.md. Questions that need CS Awesome's interactive widgets link back to it.
  2. Students do exercises 01–02, each in its own folder, pressing Run to try their code.
  3. Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.

Exercises

FolderFileGradingTests
01-unit2b-project1-gradesGrades.javaAutograded10
02-unit2b-project2-concert-tickets-loopConcertTickets.javaAutograded10

Teachers can download a reference solution after signing in.