Unit 4A Projects
From CS Awesome 2CC BY-NC-SA 4.0Original page
Java2 class periods2 exercises20 graded tests
Files
Unit 4A 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 you've learned how to create your own classes, it's time to work with collections of data using one-dimensional arrays. In these projects, you'll learn how to store, access, and manipulate multiple values efficiently. You'll practice traversing arrays, processing their elements with loops, and developing algorithms to search for information, calculate results, and modify data.
Each project is designed to reinforce these concepts through authentic programming tasks. As you complete them, focus on using loops effectively, paying close attention to array indices and boundaries, and breaking complex problems into manageable steps. Mastering one-dimensional arrays is an essential skill that prepares you for more advanced data structures and algorithms.
Review - Reading a Text File into an Instance Variable
If you have an array instance variable that is to be filled with data from a text file automatically when an object is created, the best place to do this is in the constructor. For example, the file students.txt contains:
Alice
Brian
Carlos
Diana
Emma
You want an instance variable in your class that contains the data in an array.
Code for Reading a Text File
| Description | Code |
|---|---|
| You will first need to declare a private instance variable. | private String[ ] students |
| Create a constructor for the class. The constructor should declare that it may throw an IOException. | public StudentList( ) throws IOException |
| Inside the constructor: | { |
| Create a Scanner that reads from a file named students.txt. | Scanner input = new Scanner(new File("students.txt")); |
| Create the students array with enough space to store all of the names in the file. | students = new String[5]; |
| Use a for loop to read each name from the file. | for(int i = 0; i < students.length; i++) |
| Store each name in the appropriate position of the students array. | students[i] = input.nextLine( ); |
| Close the Scanner after all names have been read. | input.close( ); |
| End of the constructor | } |
Check your understanding: Consider the following class:
import java.io.File; import java.io.IOException; import java.util.Scanner; public class StudentList { private String[] students; public StudentList() throws IOException { Scanner input = new Scanner(new File("students.txt")); students = new String[5]; for (int i = 0; i < students.length; i++) { students[i] = input.nextLine(); } input.close(); } }The file students.txt contains:
Alice Brian Carlos Diana EmmaWhich statement best explains what happens when the following line is executed?
StudentList list = new StudentList();Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/unit4a-projects.html#unit4a-project1-choose
Unit 4A Project 1 - Unit Test
Write a program that will grade a multiple choice test. This program will contain two classes: Main and UnitTest. You are to code the UnitTest class first as described below:
Unit Test Class Description
| Component | Requirement | Description |
|---|---|---|
| Class Name | UnitTest | Do not put public on the class line. |
| Instance Variables | studentAns (String [ ])<br>answerKey (String [ ]) | |
| Constructor | One parameter (String [ ]) and it will need to throw an IOException | You will need to create each instance variable to be the same length as the parameter. The studentAns variable should copy all of the elements from the parameter into itself in the same order as the parameter. You will need to make sure each element is changed to uppercase as it is being copied into the array. The answerKey variable will scan in its elements from the answerKey.txt file. |
| Methods | getStudentAnswers( ) | Returns the studentAns instance variable. |
totalCorrect( ) | This method will return the number of correctly answered questions. | |
totalMistakes( ) | This method will return the number of incorrect answers. | |
isPassing( ) | This method will return true if the student passed the test, or false if the student failed. A student must correctly answer 14 out of 20 questions in order to pass the test. | |
toString( ) | This method will return a display of the correct answers and the student answers. It must be in a side by side, 2 column format, with item numbers. See format below. |
Example output from the toString method (remember to return the String, not print it):
ANSWER KEY Student's Answers
1) B 1) A
2) D 2) A
3) C 3) C
. .
. .
. .
20) E 20) A
Hint for the toString method: Create a String and initialize it to the first line of the output using a tab between the phrases instead of spaces (\t). Create another String for the rest of your output, initializing it to the empty String. Use a for loop to concatenate onto that string the problem number (which should be one more than the index number) and the String from each array at that index with tabs between the correct answer and the student’s answer (two tabs should do it - \t\t). Return the first String, followed by a new line (\n), followed by the second String.
Once the UnitTest class is complete, you are to complete the Main class to test your UnitTest class as follows:
In the main method,
- Create a String array called answerArray of size 20.
- Create a Scanner object.
- Use a for loop to allow the user to enter their answers one at a time until they have entered all 20 answers. Store these into the answerArray as they enter them. It should not matter if they enter upper or lower case letters.
- Create a UnitTest object using the array of answers as the parameter.
- Display the following information:
- The correct answers and student’s answers using the toString method.
- Number of Correct Answers: ___ (the blank should be filled in with the appropriate value returned from the appropriate method).
- Number of Mistakes: ___ (the blank should be filled in with the appropriate value returned from the appropriate method).
- Display either “The student PASSED” or “The student FAILED” as determined by the appropriate method.
Exercise 1
Complete the UnitTest class and the Main class using the directions above.
Open the
01-unit4a-project1-unittestfolder and editMain.java. Press Run to try it; Run Tests checks it (10 tests). Run feeds it the input ininput.txt; change that file to try other input. Its tests call code you write, so they all fail until that code exists.
The data file answerKey.txt is in each exercise folder that uses it.
Review - Formatting a Double
Use String.format( ) when you want to control how a number is displayed. To format a double to two decimal places:
double price = 12.5;
String result = String.format("%.02f", price); // 12.50
Remember:
- %f → formats a double
- .02 → displays 2 digits after the decimal
- The result of String.format( ) is a String
Check your understanding: What is stored in result?
double score = 87.456; String result = String.format("%.02f", score);Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/unit4a-projects.html#unit4a-project2-double-choose
Unit 4A Project 2 - Sales Data
Write a program about sales data. This program will contain two classes: Main and SalesData. You are to code the SalesData class first as described below:
SalesData Class Description
| Component | Requirement | Description |
|---|---|---|
| Class Name | SalesData | Do not put public on the class line. |
| Instance Variable | sales (double[ ]) | |
| Constructor | One parameter (double [ ]) | Creates the sales array the same size as that parameter and copies all of the elements of the parameter array into the sales array. |
| Methods | getTotal( ) | This method returns the sum of the elements in the sales array. |
getAverage( ) | This method returns the average of the elements in the sales array. | |
getHighest( ) | This method returns the highest value stored in the sales array. | |
getLowest( ) | This method returns the lowest value stored in the sales array. | |
toString( ) | This method returns a String representation of the values stored in the sales array, one per line. Make sure the values are formatted to two decimal places and have a $ in front of the values. |
Once the SalesData class is complete, you are to complete the Main class to test your SalesData class as follows:
In the main method,
- Create a weekSales array of type double to hold sales amounts for a week (7 days).
- Use a for loop to fill the array with input from the user. Include a data verification while loop to ensure that the user is entering values greater than or equal to zero.
- Create a SalesData object named salesObject, passing in weekSales as the parameter.
- Display the total, average, highest, and lowest sales amounts for the week (be sure to format them to two decimal places) using the following format:
- Total Sales: $____
- Average Sales: $___
- Highest Sale: $___
- Lowest Sale: $___
- Display the salesObject using the toString method.
Exercise 2
Complete the SalesData class and the Main class using the directions above.
Open the
02-unit4a-project2-salesdatafolder and editMain.java. Press Run to try it; Run Tests checks it (10 tests). Run feeds it the input ininput.txt; change that file to try other input. Its tests call code you write, so they all fail until that code exists.
For teachers
Unit 4A Projects
Students read CSAwesome2's “Unit 4A 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 4: Data Collections.
Before class
- Import the lesson into your class from the Lessons page, or with New assignment → Use a lesson. It arrives as a draft with its tests already set up.
- Publish it.
- The original page, with its multiple-choice questions, is on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/unit4a-projects.html
- CS Awesome's own teacher materials: the CS Awesome teacher site
In class
- Students read
README.md. Questions that need CS Awesome's interactive widgets link back to it. - Students do exercises 01–02, each in its own folder, pressing Run to try their code.
- 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
| Folder | File | Grading | Tests |
|---|---|---|---|
01-unit4a-project1-unittest | Main.java | All or nothing until it compiles | 10 |
02-unit4a-project2-salesdata | Main.java | All or nothing until it compiles | 10 |
Teachers can download a reference solution after signing in.