Skip to main content

Section 4.71 Unit 4A Projects

These projects were created by Leigh Anne Fitz and Lisa Ferran to provide engaging, standards-aligned learning experiences for AP Computer Science A students.
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.

Subsection 4.71.1 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.
Table 4.71.1. 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
}

Activity 4.71.1.

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
Emma
Which statement best explains what happens when the following line is executed?
StudentList list = new StudentList();
  • The students array is created but remains empty until a method is called.
  • Think about when the constructor runs. Does the constructor contain code that fills the array?
  • The constructor automatically reads the five names from the file and stores them in the students array.
  • The constructor runs automatically when the object is created. It creates the array, reads each line from the file, and stores the names in the instance variable.
  • The students array is created inside the constructor and is destroyed when the constructor finishes.
  • Think about the difference between a local variable and an instance variable. Where is students declared?
  • The program reads the file only when students[i] is accessed later.
  • Look at the for loop. When does input.nextLine() actually execute? Does the program wait until an array element is accessed?

Subsection 4.71.2 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:
Table 4.71.2. Unit Test Class Description
Component Requirement Description
Class Name
UnitTest
Do not put public on the class line.
Instance Variables
studentAns (String [ ])
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.

Activity 4.71.2.

Complete the UnitTest class and the Main class using the directions above.

Subsection 4.71.3 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

Activity 4.71.3.

What is stored in result?
double score = 87.456;
String result = String.format("%.02f", score);
  • 87.456
  • Look at the .02 in "%.02f". How many digits should appear after the decimal?
  • 87.45
  • Remember that formatting to two decimal places involves rounding. Look at the third digit after the decimal.
  • 87.46
  • String.format("%.02f", score) rounds the value to two decimal places and returns it as a String.
  • 87.46 as a double
  • Think about what String.format( ) returns. Is the result a number, or is it text?

Subsection 4.71.4 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:
Table 4.71.3. 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:

Activity 4.71.4.

Complete the SalesData class and the Main class using the directions above.
You have attempted of activities on this page.