0% found this document useful (0 votes)
37 views20 pages

AP Comp Sci A 8E Practice Test 4 Answers and Explanations 12.6.24

The document provides the answer key and detailed explanations for a practice test related to AP Computer Science A. It includes multiple-choice questions with correct answers and reasoning for each choice. The explanations cover various programming concepts, including operators, loops, and methods in Java.

Uploaded by

Fan Yang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views20 pages

AP Comp Sci A 8E Practice Test 4 Answers and Explanations 12.6.24

The document provides the answer key and detailed explanations for a practice test related to AP Computer Science A. It includes multiple-choice questions with correct answers and reasoning for each choice. The explanations cover various programming concepts, including operators, loops, and methods in Java.

Uploaded by

Fan Yang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Practice Test 4:

Answers and
Explanations
AP Computer Science A Prep

PRACTICE TEST 4 ANSWER KEY

1. A 21. B
2. E 22. D
3. C 23. D
4. C 24. E
5. E 25. B
6. C 26. D
7. B 27. A
8. B 28. C
9. B 29. E
10. C 30. B
11. E 31. D
12. D 32. D
13. C 33. C
14. B 34. B
15. C 35. A
16. C 36. E
17. C 37. D
18. E 38. C
19. C 39. E
20. C 40. E

2 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

PRACTICE TEST 4 EXPLANATIONS

Section I: Multiple-Choice Questions


1. A You start with the division in the second pair of parentheses to get a result of 2.5. This is not the
final answer, however, so (B) is not correct. When this number is cast to an integer by the (int),
it truncates the decimal to result in a final value of 2. Casting to an integer never rounds, so (C) is
incorrect.

2. E The += operator is a shortcut for adding to a numeric variable. Choice (A) is incorrect because it
changes the value of num to 1 instead of adding 1. Choice (B) successfully adds 1 to the value of
num, but it does not store the new result in num, so the variable remains unchanged. Choice (C)
would be correct without the 1 at the end, but as written it would result in a syntax error. Choice
(D) is incorrect because in an assignment statement the variable being assigned a value needs to
appear on the left.

3. C The Math.random() method returns a double value greater than or equal to 0.0 and less than 1.0.
Since 0.0 is the smallest number the method can return, we need to add 5 to reach the minimum
number desired. That eliminates (A), (B), and (D). Since 1.0 is not included in the Math.random()
method, we need to multiply the result of Math.random() by the maximum number – the mini-
mum number + 1, before casting the result to (int). That would be 25 – 5 + 1, which equals 21.
This eliminates answer (E).

4. C The compareTo method returns 0 if two strings are equivalent. Since “Chicago” and “London”
are not equivalent, (A) is incorrect. The compareTo method returns the alphabetical difference
between the strings, starting with the first letter. Since C is 9 letters before L in the alphabet, the
compareTo method will return –9. This rules out (B), (D), and (E).

5. E For strings, the compareTo method will return a number less than 0 if the first string comes
before the second string alphabetically. That eliminates (A) and (D). While we don’t know how the
input from the user is implemented, if it is possible one of the cities remains null, there could be a
NullPointerException.

6. C While you could use a truth table to solve this problem, it will go much quicker if you use De Morgan’s
Laws to simplify the expression. The expression !(x < 5 && y > 10) expands to (x >= 5 || y <= 10)
so the correct answer is (C).

7. B Since result is a boolean variable, it can store only true or false. That rules out (A) and (D).
Choice (E) might seem correct because the variable num is equal to 0 and you divide by num at the
end of the expression, but there is no error because of short-circuiting. Since the first part of the
expression (num == 0) is true and the expression is combined using “or” (||), the compiler does not
need to check the second half of the expression, since it has already determined that the expression
is true.

Practice Test 4: Answers and Explanations | 3


AP Computer Science A Prep

8. B When you have an if/else if/else series, only one of the statements in the series will run.
That eliminates (D) and (E). When two objects have the same value, the == operator returns true
only if they are stored in the same location in memory. Since city and president have the same
value, but were never set equal to each other, they are not stored in the same memory location. This
eliminates (A). Using the equals method on objects checks whether they have the same value, so
the second statement will run.

9. B When you have an if/else if/else series, only one of the statements in the series will run. That
means num will either go up by 1 (the if or else if statement) or be set equal to 10. This elimi-
nates (A), (C), and (D). The if statement condition (num < 10) is true, since num is equal to 0 at
the start. That means that num will be increased by 1.

10. C This question is almost equivalent to question 9. The only difference is the else if from question
9 is an if statement in question 10. We already know that the first if statement runs, so num will
not remain 0, eliminating (A). Since num is 1 when the second if statement (num == 1) is evalu-
ated, num is again increased by 1, to reach 2. The else statement does not run because exactly one
statement runs in an if/else pair.

11. E We know that the first if statement runs, since it is equivalent to the first statements in the previ-
ous two questions, so num will not remain 0, thus eliminating (A). The else if statement does
not run because exactly one statement in an if/else if pair will run. Since num is equal to 1
when we get to the second if statement (num == 2), it will run the else statement, making num
equal 10 when the code is complete.

12. D The condition of the while loop is num < 10. That means the loop will run as long as num is less
than 10. Since num starts at 0, the loop will run at least once. This eliminates (A). The body of the
loop increases num by 1 (num++) and since the loop runs 10 times (0…9), num will equal 10 when
the loop ends.

13. C The condition of the while loop is num < 10. That means the loop will run as long as num is less
than 10. Since there is an if/else pair in the loop and num increases in the if and the else, num
will eventually become 10 or greater. This eliminates (E). The modulus operator (%) returns the
remainder of division. The num % 2 == 0 condition is checking to see whether num is divisible
by 2. The variable num is divisible by 2 when it is 0, so num goes up to 1. When num is 1, it is not
divisible by 2, so it is instead multiplied by 2 to go up to 2. 2 is divisible by 2, so num becomes 3.
3 is not divisible by 2, so num becomes 6. 6 is divisible by 2, so num becomes 7. 7 is not divisible by
2, so num becomes 14. Since 14 is not less than 10, the loop ends.

14. B The condition must be a condition that will be true when num is 1; otherwise the loop won’t run.
This eliminates (A), (D), and (E). If the condition is true when num is equal to 4, that will cause it
to run one extra time and num will end up equal to 8, so this eliminates (C).

4 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

15. C Since i and num are both equal to 0 when the for loop starts, (E) would cause the loop not to run
at all. Since we want the loop to stop based on the value of num, we should be using num in the
condition, which eliminates (A) and (B). If the loop continues to run when num equals 10, its value
will go beyond 10, so we don’t want the condition that checks whether num is <= 10. Eliminate
(D); (C) is the correct answer.

16. C The loop variable i increases by 2 each time the loop runs (i += 2), so i will equal 0, 2, 4, 6,
8, and 10 while the loop is running. Once i becomes 12, the loop will end. That means the loop
body will run 6 times.

17. C The loop will start at 1000 (int i = 1000) and count down by 1 (i--) to 0, but not include 0.
This means it will run 1000 times.

18. E The outer for loop will run 5 times (i = 0…i = 4). The inner for loop will run 2 times (k = 0…
k = 1). This will cause the inner for loop body to run a total of 10 times (5 × 2), causing num to
increase until it has a value of 10.

19. C The loop will add a single character from firstString to secondString each time the loop runs.
Using the substring method with i and i + 1 as the arguments causes it to add a character
at a time. Since the loop runs 5 times (0…4), it will add the first 5 characters from firstString,
“missi”, to secondString.

20. C This question uses an enhanced-for loop, also known as a for-each loop. An enhanced-for loop
looks at each element in a collection and stores it in a temporary variable. The temporary variable
in this case is called city. Since an enhanced-for loop looks at every element and there are no
errors in the code, we can eliminate (A) and (E). Since a println statement is used, the loop will
print each element on a separate line. This eliminates (B). Finally, an enhanced-for loop prints the
elements from the collection in the same order, so Chicago will be printed first and Manila will
be printed last. Eliminate (D); the correct answer is (C).

21. B When you are trying to set the value of a variable that already exists, you shouldn’t precede the
variable name with the variable type. This eliminates (C), (D), and (E). The variable you are trying
to change should come before the =, so firstName, lastName, and number should be to the left
of the =.

22. D You should never return something from a void method, so that eliminates (A) and (B). As stated
in the explanation for question 21, you shouldn’t precede a variable name with the variable type
if you are trying to change the value of an already existing variable. That eliminates (E). Since
position is the variable you are trying to change, it should come to the left of the =.

23. D You should not change the names of any variables you are given. Doing so could cause problems
elsewhere in the program. This eliminates (A) and (B). The this keyword is used to access class-
level variables if you have local variables with the same names.

Practice Test 4: Answers and Explanations | 5


AP Computer Science A Prep

24. E When you initialize a new array, you need to initialize it with the size and variable type. That
eliminates (C) and (D). You also need to put [ ] after the variable type when you declare the array,
which eliminates (A) and (B).

25. B The compareTo method returns a number less than 0 if the first string comes before the second
string. That rules out (A), (C), and (E). The loop continues to run over the entire length of the
array, so it will eventually find the string that comes first alphabetically.

26. D The variable x is going up by only 1 (x++) each time the if statement is true, so the code can’t be
getting a total of the numbers. This eliminates (B) and (C). The if statement uses modulus (%) to
determine whether the current number in the array is even, since an even number has no remainder
when it is divided by 2.

27. A Since array indices start at 0, the 10th element of an array would have index 9. That eliminates (B),
(D), and (E). Choice (C) is not correct either, since it is attempting to set the array equal to 9 rather
than accessing index 9 using square brackets [ ].

28. C You can use a binary search on any data structure, so that rules out (A), (B), and (E). Binary search
can also be used on any primitive type (such as integers, doubles, and booleans) or any comparable
type (such as strings), which rules out (D).

29. E Selection sort works by finding the minimum element and swapping it with the first element. It
then moves to the second element and finds the second-smallest element. Bubble sort and quick
sort are not tested on the AP Computer Science A exam, while Insertion sort inserts smaller ele-
ments before larger ones and Merge sort divides the array into halves, sorts, and then merges.

30. B The substring method will look at the first letter of each element of myList (which are stored
in the temp variable) and determine whether it is equal to “s”. The variable x will increment by 1
(x++) for each element that starts with “s”.

31. D When initializing a 2D array, you declare the number of rows in the first pair of square brackets
and the number of columns in the second pair. That eliminates (A), (C), and (E), since they declare
10 rows instead of 5 rows. Choice (B) is incorrect because it does not have two pairs of square
brackets after the variable type to the left of the equals sign.

32. D The nested for-each loops will iterate through the entire 2D array. Since the code is adding temp
to the variable x (x += temp), that will result in a sum of all of the values in the 2D array being
stored in x.

33. C Getting the length of a 2D array gives you the number of rows. This eliminates (A) and (B). You
need to access an element in a row of the 2D array and get its length to determine the number of
columns. You can do this by using myArray[0].length or myArray[row].length.

6 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

34. B When you are creating a class that is a subclass of another class, you need to use the extends key-
word. This eliminates (A), (C), and (E). You always put the name of the current class directly after
the keyword class, which eliminates (D).

35. A When declaring a constructor, there is no return type as there would be in a normal method.
Removing the void keyword would fix the error. Line 2 correctly sends the name to the superclass
constructor and line 3 correctly initializes the class-level variable salary.

36. E Abstraction is hiding the details of how something works and just focusing on what it does. For
example, you may use the substring method quite a bit, but you don’t need to know how it
actually calculates the substring you ask for in order to use it. Inheritance allows code reusability
between classes. Encapsulation hides unnecessary details through the use of private variables and
methods. Polymorphism allows different types of objects to share methods, even though some of
those methods may be executed in different ways.

37. D The Object class is the superclass for all other classes in Java.

38. C The base case is the value that will be returned that stops the code making recursive calls. You can
see that line 6 makes a recursive call, so that rules out (D). The actual base case is when the value of
the base case is set, which is why (B) and (E) are not correct.

39. E Here is what the recursive calls look like:

sum(5) = 5 + sum(4)

sum(4) = 4 + sum(3)

sum(3) = 3 + sum(2)

sum(2) = 2 + sum(1)

sum(1) = 1

Going back through the stack of recursive calls:

sum(2) = 2 + 1 = 3

sum(3) = 3 + 3 = 6

sum(4) = 4 + 6 = 10

sum(5) = 5 + 10 = 15

Practice Test 4: Answers and Explanations | 7


AP Computer Science A Prep

40. E This problem can be solved by creating a tree of the recursive calls. Based on the tree below, you
can see there are 15 recursive calls.

fib(5)

fib(4) fib(3)

fib(3) fib(2) fib(2) fib(1)

fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)

fib(1) fib(0)

8 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

Section II: Free-Response Questions


1. (a) Sample Answer #1
private Elective getElectiveByName (String name)
{
for (int eIndex = 0; eIndex < this.getElectiveListSize(); eIndex++)
{
Elective e = electiveList.get(eIndex);
String eName = e.getName();
if (name.equals(eName))
return e;
}
return null;
}

Sample Answer #2
private Elective getElectiveByName (String name)
{
int index;
for (int eIndex; getElectiveList)
{
Elective e = electiveList.get(eIndex);
String eName = e.getName();
if (name.equals(eName))
index = eIndex;
}
return electiveList.get(index);
}

Sample Answer #3
private Elective getElectiveByName (String name)
{
int eIndex = 0;
while (eIndex < this.getElectiveListSize())
{
Elective e = electiveList.get(eIndex);
String eName = e.getName();
if (name.equals(eName))
Return e;
eIndex++
}
return null;
}

The goal of the method is to return the Elective with the name matching the parameter. Go
through electiveList using either a while loop, for loop, or enhanced-for loop. At each index
of electiveList, the method must determine whether the name of the Elective matches the
parameter String name. Remember that since name is a private variable, it cannot be called by
another class, so the public method getName() must be used. Also, when comparing Strings, the
== operator cannot be used, because this operator tests whether the objects are the same rather
than whether two objects have the same value. To test whether two objects have the same value,

Practice Test 4: Answers and Explanations | 9


AP Computer Science A Prep

the equals() method of the String class must be used. Once a match is found, there is no need
to continue execution of the method, so the Elective with the matching name can be returned.
Because a precondition indicates there will be a match, this return statement will be reached. How-
ever, the compiler will not recognize this. In order to avoid a compile-time error, there must be a
return statement in a non-conditional statement, so add a null return (or any other return). An
alternative method is to record the index of the match. After searching all indexes, return the
Elective at the recorded index of electiveList.

(b) Sample Answer #1


public void assignElectivesToStudents()
{
for (int sIndex = 0; sIndex < this.getStudentListSize(); sIndex++)
{
Student s = studentList.get(sIndex);
int choice = 0;
while (choice < 3 && !s.hasElective())
{
String name = s.getChoice(choice);
Elective e = getElectiveByName(name);
if (e.getClassSize() < e.getMaxClassSize())
{
e.addStudent(s);
s.assignElective(e);
}
choice += 1;
}
}
}

Sample Answer #2
public void assignElectivesToStudents()
{
for (int sIndex: this.getStudentListSize())
{

for (int choice = 0; choice < 3; choice++)
{
String name = studentList.get(sIndex).getChoice(choice);
Elective e = getElectiveByName(name);
if (e.getClassSize() < e.getMaxClassSize() &&
!studentList.get(sIndex).hasElective())
{
e.addStudent(studentList.get(sIndex));
s.assignElective(e);
}
}
}
}

10 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

The method must assign each student to his or her first available choice of elective. Go through all
the students, in order, using a for loop, an enhanced-for loop, or a while loop. For each student,
go through the student’s three choices, in order, using another loop (which also could be any of
the three listed above). For each choice, use the getElectiveByName() method from part (a) to
find the matching Elective object, and assign the student to the class if there is room in the class
(i.e., the class size is less than the max class size) and the student remains unassigned to an elective
(i.e., the student’s hasElective() method returns false). A student must be assigned to an elective
using the assignElective() and the student must be added to the Elective’s student list using
the elective’s addStudents() method.

(c) Sample Answer:


public ArrayList studentsWithoutElectives()
{
ArrayList<Student> result = new ArrayList<Student>();
for (int sIndex = 0; sIndex < this.getStudentListSize(); sIndex++)
{
Student s = studentList.get(sIndex);
if (!s.hasElective())
result.add(s);
}
return result;
}

The goal of the method is to go through each student and return an ArrayList of students who
have been unassigned. First create an empty ArrayList of Student objects to be returned. Go
through the school’s student list using a for loop, an enhanced-for loop, or a while loop. At
each index, if the student at that index is unassigned (i.e., if the hasElective() method returns
false), add the student to the ArrayList. After the end, return the ArrayList.

2. (a) Sample Answer #1


public boolean inOrder()
{
for (int k = 0; k < cards.length; k++)
{
if (cards[k] != k)
return false;
}
return true;
}

Practice Test 4: Answers and Explanations | 11


AP Computer Science A Prep

Sample Answer #2
public boolean inOrder()
{
boolean temp = true;
int k = 0;
while (k < cards.length && temp)
{
if (cards[k] != k)
temp = false;
k++;
}
return temp;
}

Sample Answer #3
public boolean inOrder()
{
boolean temp = true;
for (int k : cards)
{
if (!(cards[k] == k))
temp = false;
}
return temp;
}

The goal of the method is to determine whether the deck is in order and return the appropriate
boolean. Because the cards in a deck of length n are numbered 0 through n − 1, an ordered deck
will have all the values matching their indexes. Go through each card in the deck one at a time
using a for loop, an enhanced-for loop, or a while loop. A deck is ordered only if all the card val-
ues match their indexes. If even one card value does not match the index, the method must return
false. Therefore, the return false statement can be made immediately upon finding the card that
doesn’t match the index. If false is never returned in the for loop, then true must be returned. As
an alternative, create a boolean outside the loop set to true. Set it to false if any card is found for
which the value does not match the index. Then return the boolean after the loop.

(b) Sample Answer #1


public void shuffle()
{
int[] newCards = new int[cards.length];
for(int k = 0; k < cards.length/2; k++)
{
newCards[k*2] = cards[k];
newCards[k*2+1] = cards[cards.length/2+k];
}
cards = newCards;
}

12 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

Sample Answer #2
public void shuffle()
{
int[] newCards = new int[cards.length];
for(int k : newCards)
{
if (k%2 == 0)
newCards[k] = cards[k/2];
else
newCards[k] = cards[cards.length/2+k/2];
}
cards = newCards;
}

Sample Answer #3
public void shuffle()
{
int[] front = new int[cards.length/2];
for (int k = 0; k < front.length; k++)
front[k] = cards[k];
int[] back = new int[cards.length/2];
for (int k = 0; back.length; k++)
back[k] = cards[back.length + k];
int[] newCards = new int[cards.length]
int j = 0;
while(j < newCards.length)
{
if (k % 2 == 1)
newCards[k] = back[cards.length/2];
else
newCards[k] = front[k/2];
}
cards = newCards;
}

The goal of this method is to rearrange the values in cards according to the method described in
the question. To do this, the deck must be split into a front half and a back half; then the cards
must alternate, beginning with the front half. One possible approach is to directly separate the
deck, as is done in Sample Answer #3. This is not necessary, though, as long as you place the first
card of the deck in index 0 of the shuffled deck, the first card of the second half in index 1, the
second card of the first half in index 2, the second card of the second half in index 3, and so on. A
new deck of the same length as the original deck must be created. Copy the card from the original
deck into the new deck, using one of the methods described above. The return is void, so the deck
represented by the int array cards must be assigned the values of the new deck.

Practice Test 4: Answers and Explanations | 13


AP Computer Science A Prep

(c) Sample Answer #1


public int reorderingCount()
{
int count = 0;
while (!inOrder() || count == 0)
{
shuffle();
count += 1;
}
return count;
}

Sample Answer #2
public int reorderingCount()
{
Shuffle();
int count;
for (count = 1; !inOrder(); count++)
shuffle();
return count;
}

The goal of the method is to shuffle the deck repeatedly until it is back in its original order, and
return the number of times it was shuffled. Create a counter by initializing an int and setting it
equal to zero. Make sure to shuffle at least once. Use a for or while loop to do repeated shuffles
until the deck is back in order, incrementing the counter at each shuffle, including the first. The
loop must stop when the deck is back in order, so it must continue while inOrder() is false.
After it is back in order, the loop must terminate, and the counter variable must be returned by the
method.

14 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

3. (a)
public class Recipe
{
private String name;
private ArrayList<Ingredient> ingredientList;
private String preparationProcess;
private int numberServed;
public ArrayList<Ingredient> getIngredientList()
{ /* implementation not needed */ }
public Recipe(String recipeName, int numServed)
{ /* implementation not needed */ }
public void addIngredient(Ingredient newIngredient)
{ /* implementation not needed */ }
public void setPreparationProcess(String newPreparationProcess)
{ /* implementation not needed */ }
public String getName()
{ /* implementation not needed */ }
public int getNumberServed()
{ /* implementation not needed */ }
public void scale(int newNumberServed)
{ /* implementation not needed */ }
}
Be sure to list all the needed variables with the appropriate data types as described in the ques-
tion. Both the name of the recipe and the description of the preparation process are text, so use
String types. The list of ingredients will need to be of a variable size, so use an ArrayList. Use
an int for the numberServed. Also be sure to list the method signatures as described in the ques-
tion. To create a recipe with a given name and number of people served, use a constructor method
with String and int parameters. To add an ingredient, use a method that takes an ingredient as a
parameter. Since this method will alter the already existing ingredients list within the Recipe
object rather than create a new list, the return should be void. Similarly, the method to set the
description will alter an already existing data within the Recipe object, so take a String param-
eter and have a void return. To return the name of the recipe, number of people served, or the list
of ingredients, take no parameters and return the appropriate data type. The method to scale the
amount based on a new number of people served must take the new number of people served as
a parameter and alter already existing Ingredient objects and the NumberServed integer so it
should have a void return.

Practice Test 4: Answers and Explanations | 15


AP Computer Science A Prep

(b) Sample Answer #1


public void scale(int newNumberServed)
{
double oldAmount;
double newAmount;
for (int k = 0; k < ingredientList.size(); k++)
{
Ingredient ingred = (Ingredient) ingredientList.get(k);
oldAmount = ingred.getAmount();
newAmount = newNumberServed * (oldAmount / numberServed);
ingred.setAmount(newAmount);
}
numberServed = newNumberServed;
}

Sample Answer #2
public void scale(int newNumberServed)
{

for (Ingredient in : IngredientList)


{
double oldAmount = in.getAmount();
double newAmount = newNumberServed * (oldAmount / numberServed);
in.setAmount(newAmount);
}
numberServed = newNumberServed;
}
There are two goals for this recipe. One is to change the number of people served by the recipe.

This can be achieved by one command: setting the class variable for the number of people served

equal to the parameter. However, this should be done at the end of the method, so that the original

number of people served can be used. The other goal is to scale the amount of each ingredient to

the new number of people. Go through each ingredient in ingredientList using a for loop,

an enhanced-for loop, or a while loop. For each ingredient, record the original amount. Get

the new amount by using an appropriate scaling. To determine how to do this, use a proportion:
oldAmount numberServed
= . To find an expression for newAmount, cross-multiply to get
newAmount newNumberServed
newAmount * numberServed = oldAmount * newNumberServed. Divide both sides by

numberServed to get newAmount = (oldAmount * newNumberServed) / numberServed. (An

alternative but equivalent formula is shown in Sample Answer # 1.) Use the setAmount() method

of the ingredient, passing newAmount as a parameter to update the amount of the ingredient.

Finally, end the loop and set the number served to the new amount as discussed above.

16 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

(c) Sample Answer #1


public void standardize(int numPeople)
{
for (int j = 0; j < recipeList.size(); j++)
{
recipeList.get(j).scale(numPeople);
}
}

Sample Answer #2
public void standardize(int numPeople)
{
int j = 0
while (j < recipeList.size())
{
recipeList.get(j).scale(numPeople);
j++;
}
}

The goal of the method is to apply the setAmount() method to all recipes using a predetermined
number of people. Take the number of people as a parameter. Because the method is intended to
alter already existing objects rather than create new objects, the return should be void. Go through
each recipe using a for loop, an enhanced-for loop, or a while loop. For each recipe, use an inner
loop of any of the three types to go through each ingredient and scale it to the new amount. This
can be done in a similar method to what was done in part (b) or can be done simply by using the
scale method.

Practice Test 4: Answers and Explanations | 17


AP Computer Science A Prep

4.
public class School
{
private ArrayList<Classroom> classrooms;
public School(ArrayList<Classroom> schoolRooms)
{
classrooms = SchoolRooms;
}
public String findStudent(String teacher, int IDnumber)
{
for (int k = 0; k < classrooms.size(); k++)
{
if (classrooms.get(k).getTeacherName().equals(teacher))
{
int low = 0;
int high = classrooms.get(k).getStudents().size() – 1;
while (low <= high)
{
int middle = (low + high) / 2;
if (IDnumber < classrooms.get(k).getStudents().
get(middle).getStudentID())
{
high = middle − 1;
}
else if (IDnumber >
classrooms.get(k).getStudents().get(middle).getStudentID())
{
low = middle + 1;
}
else
{
return classrooms.get(k).getStudents().
get(middle).getStudentName();
}
}
}
}
return “Student Not Found”;
}
}

18 | Practice Test 4: Answers and Explanations


AP Computer Science A Prep

public class Classroom


{
private String teacherName;
private ArrayList<Student> Students;
public Classroom(String teacher, ArrayList<Student> theStudents)
{
teacherName = teacher;
Students = theStudents;
}
public String getTeacherName()
{
return teacherName;
}
public ArrayList<Student> getStudents()
{
return Students;
}
}

public class Student


{
private String studentName;
private int studentID;
public Student(String name, int ID)
{
studentName = name;
studentID = ID;
}
public int getStudentID()
{
return studentID;
}
public String getStudentName()
{
return studentName;
}
}
The question specifies that there must be three classes: School, Classroom, and Student. Create
a class definition for each, including a constructor taking the required data fields as parameters.
School must take ArrayList<Classroom> schoolRooms, Classroom must take String
teacherName and ArrayList<Student> theStudents, and Student must take String
name and int ID. The only method specified by the question is findStudent in the School class.
However, the description of this method indicates that it will require information from Class-
room and Student objects. Since, on the AP Exam, all variables should be specified as private,
this will require the use of public methods in the Classroom and Student classes. The vari-
ables in Classroom are teacherName and students, so create a getTeacherName() method
returning a String with the same value as teacherName and a getStudents to return the
ArrayList Students. The variables in Student are studentID and studentName, so create
a getStudentID() method returning an integer equal to studentID and a getStudentName()
method returning a String with the same value as studentName.

Practice Test 4: Answers and Explanations | 19


AP Computer Science A Prep

To create the findStudent method, the question specifies that it must take a String for teacher
name and an integer for student ID as parameters. The question also specifies that a sequential
search must be used to find the classroom based on teacher name. A sequential search can be
most easily accomplished using a for loop or an enhanced-for loop (though a while loop is also
possible). Search through the entire list of classrooms, one at a time, to determine whether the
teacher parameter matches the teacherName in the Classroom. To do this, be sure to get the
getTeacherName() method of the Classroom object, since teacherName is a private variable.
Also, be sure to use the equals() method of the String class, since the == operator returns true only
if the String objects are the same name rather than if they have the same value. If a match is found,
search the classroom for the student using ID. The question specifies that a binary search must be
used. Use a standard binary search. If a match is found, return the name of the student using the
getStudentName() method of the Student object. If no match is found, nothing will be returned
by the searches. Outside the two searches, return “Student Not Found” as specified by the
question.

Copyright © 2023 by TPR Education IP Holdings, LLC. All rights reserved.

20 | Practice Test 4: Answers and Explanations

You might also like