5 Steps to a 5 AP Computer Science A 2017 (2016)

STEP 5

Building Your Test-Taking Confidence

AP Computer Science A Practice Exam 1

AP Computer Science A Practice Exam 2

AP Computer Science A: Practice Exam 1

Multiple-Choice Questions

ANSWER SHEET

AP Computer Science A: Practice Exam 1

Part I (Multiple Choice)

Time: 90 minutes
Number of questions: 40
Percent of total score: 50

Directions: Choose the best answer for each problem. Some problems take longer than others. Consider how much time you have left before spending too much time on any one problem.

Notes:

  • You may assume all import statements have been included where they are needed.
  • You may assume that the parameters in method calls are not null.
  • You may assume that declarations of variables and methods appear within the context of an enclosing class.

1 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   9

(B)   10

(C)   7

(D)   30

(E)   21

2 .    Assume that a , b , and c have been declared and correctly initialized with int values. Consider the following expression.

Under what conditions does bool evaluate to true?

(A)   a = 1 , b = 2 , c = 3

(B)   a = 3 , b = 2 , c = 1

(C)   a = 3 , b = 1 , c = 2

(D)   All conditions; bool is always true .

(E)   No conditions; bool is always false .

3 .    Consider the following code segment.

What values are stored in myArray after executing the code segment?

(A)   {2, 3, 4, 1, 7, 6, 8}

(B)   {2, 3, 4, 1, 7, 9, 11}

(C)   {5, 6, 7, 4, 7, 9, 8}

(D)   {5, 6, 7, 4, 7, 6, 8}

(E)   {5, 6, 7, 4, 0, 9, 11}

4 .    Consider the following interface used by a company to represent the items it has available for online purchase.

The company bills at the end of the quarter. Until then, it uses an ArrayList of OnlinePurchaseItem objects to track a customer’s purchases.

The company decides to offer a 20 percent off promotion on all items purchased in September. Which of the following code segments properly calculates the correct total price at the end of the quarter?

III.  

(A)   I only

(B)   II only

(C)   I and II only

(D)   II and III only

(E)   I, II, and III

5 .    Consider the following method.

What value is returned by the call mystery(5) ?

(A)   1

(B)   7

(C)   8

(D)   9

(E)   10

6 .    Consider the following code segment.

What is the value of myString after executing the code segment?

(A)   "H"

(B)   "AHA"

(C)   "AAAHAAA"

(D)   "AAAAHAAAA"

(E)   "AAAAAAHAAAAAA"

7 .    Consider the following statement.

What are the possible values of var after executing the statement?

(A)   All integers from 1 to 59 (inclusive)

(B)   All integers from 10 to 59 (inclusive)

(C)   All integers from 10 to 60 (inclusive)

(D)   All real numbers from 50 to 60 (not including 60)

(E)   All real numbers from 10 to 60 (not including 60)

8 .    Consider the following statement.

What is printed as a result of executing the statement?

(A)   136APCS(9 - 5)4

(B)   19APCS8

(C)   19APCS44

(D)   136APCS8

(E)   136APCS44

9 .    Consider the following method.

What is the value of num after executing the following code statement?

(A)   6

(B)   7

(C)   10

(D)   Nothing is returned. Modulus by 0 causes an ArithmeticException .

(E)   Nothing is returned. Infinite recursion causes a stack overflow error.

10 .    Consider the following class.

Consider the following code segment that appears in another class.

What is printed as a result of executing the code segment?

(A)   Ford Spectre

(B)   Ford Fusion

(C)   Kia Spectre

(D)   Toyota Corolla

(E)   Toyota Spectre

Questions 11–14 refer to the following class definition.

11 .    The Depot class has three constructors. Which of the following is the correct term for this practice?

(A)   Overriding

(B)   Procedural abstraction

(C)   Encapsulation

(D)   Polymorphism

(E)   Overloading

12 .    Consider the following code segment in another class.

What is printed as a result of executing the code segment?

(A)   California, Oakland USA true

(B)   California, Oakland USA active

(C)   USA, California USA true

(D)   Oakland, California USA active

(E)   Oakland, California USA true

13 .    Consider the following class definition.

Which of the following constructors compiles without error?

III.  

(A)   I only

(B)   II only

(C)   III only

(D)   II and III only

(E)   I, II, and III

14 .    Assume a correct no-argument constructor has been added to the WhistleStop class.

Which of the following code segments compiles without error?

III.  

(A)   I only

(B)   I and II only

(C)   I and III only

(D)   II and III only

(E)   I, II, and III

15 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   nicraz

(B)   nieicr

(C)   nieicraz

(D)   einicraz

(E)   weienicraz

16 .    Consider the following method.

Which of the following sets of data tests every possible path through the code?

(A)   -6, -1, 15, 12

(B)   -5, -3, 12, 15

(C)   -8, -5, 8, 10

(D)   -6, 0, 20, 7

(E)   -10, -5, 10, 12

Questions 17–18 refer to the following scenario.

A resort wants to recommend activities for its guests, based on the temperature (degrees F) as follows:

17 .    Consider the following method.

Consider the following statement.

For which temperature range is the correct suggestion printed (as defined above)?

(A)   temperature > 75

(B)   temperature > 60

(C)   temperature > 45

(D)   temperature <= 60

(E)   Never correct

18 .    After discovering that the method did not work correctly, it was rewritten as follows.

Consider the following statement.

What is the largest temperature range for which the correct suggestion is printed (as defined above)?

(A)   Always correct

(B)   Never correct

(C)   temperature <= 75

(D)   temperature <= 60

(E)   temperature <= 45

19 .    Assume int[] arr has been correctly instantiated and is of sufficient size. Which of these code segments results in identical arrays?

III.  

(A)   I and II only

(B)   II and III only

(C)   I and III only

(D)   I, II, and III

(E)   All three outputs are different.

20 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   [Canada, Russia, France]

(B)   [Cambodia, Russia, France]

(C)   [Australia, Cambodia, Russia, France]

(D)   [Canada, Cambodia, Russia, France]

(E)   Nothing is printed. IndexOutOfBoundsException

21 .    Consider the following method.

Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   1

(B)   3

(C)   4

(D)   5

(E)   6

Questions 22–23 refer to the following class.

Consider the following code segment.

22 .    Which of the following calls returns the value 20?

(A)   c1.getX()

(B)   c1.getY()

(C)   c2.getX()

(D)   c2.getY()

(E)   c3.getX()

23 .    Which of the following calls returns the value 30?

(A)   c1.getX()

(B)   c2.getX()

(C)   c3.getX()

(D)   All of the above

(E)   None of the above

Questions 24–25 refer to the following interface and class.

24 .    Consider the following class declarations.

III.  

Which of the declarations does not cause an error?

(A)   I and II only

(B)   II and III only

(C)   III and IV only

(C)   I and III only

(E)   I and IV only

25 .    Consider the following interface.

Which of the following class declarations does not cause an error?

(A)   public class A extends Supernatural implements FictionalCharacter

(B)   public class B extends BabyWolf, WereWolf implements FictionalCharacter

(C)   public class C implements Supernatural, Werewolf

(D)   public class E extends FictionalCharacter

(E)   public class D extends Werewolf implements Supernatural, FictionalCharacter

Questions 26–28 refer to the following classes.

26 .    Which of the following is a correct implementation of a Child class constructor?

(A)   

(B)   

(C)   

(D)   

(E)   

27 .    Which of the following is a correct implementation of the Adult class toString method?

(A)   

(B)   

(C)   

(D)   

(E)   

28 .    Consider the following method declaration in a different class.

Assume the following variables have been correctly instantiated and initialized with appropriate values.

Which of the following method calls compiles without error?

  1. findSomeone(p);
  2. findSomeone(a);

III.  findSomeone(c);

  1. findSomeone((Adult) p);
  2. findSomeone((Adult) c);

(A)   II only

(B)   I and II only

(C)   II and IV only

(D)   II, IV, and V only

(E)   II, III, and IV only

29 .    Consider the following method. The method is intended to return true if the value val raised to the power power is within the tolerance tolerance of the target value target , and false otherwise.

public boolean similar(double val, double power, double target, double tolerance)

Which code segment below can replace /* missing code */ to make the method work as intended?

(A)   

(B)   return (Math.abs(Math.pow(val, power))) - target <= tolerance;

(C)   double answer = Math.pow(Math.abs(val), power);
return answer - target <= tolerance;

(D)   double answer = Math.pow(val, power) - target;
boolean within = answer - tolerance >= 0; 
return within;

(E)   return (Math.abs(Math.pow(val, power) - target) <= tolerance);

30 .    Consider the following method.

public int changeEm(int num1, int num2, int[] values)

Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   num1 = 2  values[4] = 4

(B)   num1 = 2  values[4] = 5

(C)   num1 = 2  values[4] = 3

(D)   num1 = 4  values[3] = 3

(E)   num1 = 4  values[3] = 4

Questions 31–32 refer to the following information.

In computer graphics, RGB colors can be specified several ways.

  • Colors can be represented by ordered triples in which the first number represents red, the second green, and the third blue. The three numbers range in value from 0 to 255 (inclusive).
  • Colors can be represented by a single six-digit hexadecimal number written with a # in front of it.

These two representations have a simple relationship. The leftmost two digits of the hexadecimal number are a direct conversion from decimal to hexadecimal of the red value in the ordered triple, the middle two digits are a direct conversion of the green value in the ordered triple, and the rightmost two digits are a direct conversion of the blue value in the ordered triple.

For example, the ordered triple (10, 16, 20) becomes #0A1014 in hexadecimal form since 10 0A, 16 10, and 20  14, and the hexadecimal #110F03 becomes the ordered triple (17, 15, 3).

31 .    Convert the RGB ordered triple (125, 200, 78) to hexadecimal form.

(A)   12520078

(B)   7DC84E

(C)   713128414

(D)   202018

(E)   84D452

32 .    Convert the RGB color #EA27B5 in hexadecimal form to an ordered triple.

(A)   (1410, 27, 115)

(B)   (204, 40, 115)

(C)   (234, 39, 181)

(D)   (221, 39, 171)

(E)   (24, 39, 16)

33 .    A programmer intends to apply the standard Binary Search algorithm on the following array of integers. The standard Binary Search algorithm returns the index of the search target if it is found and -1 if the target is not found. What is returned by the algorithm when a search for 50 is executed?

(A)   -1

(B)   0

(C)   5

(D)   6

(E)   7

34 .    Consider the following code segment.

What are the values in array nums after the code segment is executed?

(A)   { {0, 1, 0}, {3, 4, 3}, {6, 7, 6} }

(B)   { {0, 0, 0}, {3, 3, 3}, {6, 6, 6} }

(C)   { {2, 1, 0}, {5, 4, 3}, {8, 7, 6} }

(D)   { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} }

(E)   { {8, 7, 6}, {5, 4, 3}, {2, 1, 0} }

35 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   [2, 4, 5]

(B)   [2, 2, 1]

(C)   [2, 4, 3, 5, 1]

(D)   [1, 2, 3, 3, 4, 5]

(E)   [2, 4, 3, 3, 5, 1]

36 .    Consider the following code segment.

What is printed as a result of executing the code segment?

(A)   9 9 9

(B)   0 0 0

(C)   0 3 9

(D)   9 3 9

(E)   9 3 0

37 .    Consider the following sorting method.

Consider the following code segment.

Which of the following shows the elements of the array in the correct order after the second pass through the outer loop of the sorting algorithm?

(A)   {0, 1, 2, 9, 3}

(B)   {0, 1, 3, 9, 2}

(C)   {0, 1, 9, 3, 2}

(D)   {1, 3, 9, 0, 2}

(E)   {1, 3, 0, 2, 9}

38 .    Consider the following method.

What is returned by the method call puzzle(3, 4) ?

(A)   9

(B)   64

(C)   81

(D)   128

(E)   Nothing is returned. Infinite recursion causes a stack overflow error.

39 .    Consider the following code segment.

What is the value of table[3][4] after executing the code segment?

(A)   22

(B)   30

(C)   34

(D)   42

(E)   46

40 .    Consider the following method.

Assume String[] ray has been properly instantiated and populated with String objects.

Which line of code should replace /* missing code */ so that the method call selectionSort(ray) results in an array whose elements are sorted from least to greatest?

(A)   if (arr[j].equals(arr[small])

(B)   if (arr[j] > arr[small])

(C)   if (arr[j] < arr[small])

(D)   if (arr[j].compareTo(arr[small]) > 0)

(E)   if (arr[j].compareTo(arr[small]) < 0)

STOP. End of Part I.

AP Computer Science A: Practice Exam 1

Part II (Free Response)

Time: 90 minutes
Number of questions: 4
Percent of total score: 50

Directions: Write all of your code in Java. Show all your work.

Notes:

  • You may assume all imports have been made for you.
  • You may assume that all preconditions are met when making calls to methods.
  • You may assume that all parameters within method calls are not null.
  • Be aware that you should, when possible, use methods that are defined in the classes provided as opposed to duplicating them by writing your own code.

1 .    A regular hexagon is a six-sided geometric figure in which all six sides are the same length and all the interior angles measure 120 degrees.

A regular hexagon is represented by the RegularHexagon class. The RegularHexagon class uses the CoordinatePoint class to specify its vertices (corners). The CoordinatePoint class represents a point on the coordinate plane.

(a)   Write the getSideLength method for the RegularHexagon class. The side length is found by calculating the distance between two consecutive coordinate points. The formula for computing distance is:

Example

Suppose two consecutive coordinate points of the regular hexagon are (1, 3) and (2, 4). The side length of the regular hexagon is:

Complete the method getSideLength .

(b)   Write the getArea method for the RegularHexagon class. The formula for computing the area of a regular hexagon is:

Example:

Suppose a regular hexagon has a side length of 5. Its area is:

You may assume that the getSideLength method works as intended, regardless of what you wrote in part (a).

Complete the method getArea .

(c)   Write the getCenter method for the RegularHexagon class. The center of a regular hexagon is located at the midpoint of any diagonal of a regular hexagon.

A diagonal of a regular hexagon is a line segment that connects two points that lie opposite each other on the hexagon.

Point 0 and point 3 are endpoints of a diagonal, as are points 1 and 4, and points 2 and 5.

The midpoint formula is:

Example

Given a RegularHexagon object with its first vertex at (2, 5) and its fourth vertex at (4, 3), the center of the hexagon is:

2 .    A train is composed of an engine and any number of train cars. The engine is rated to pull up to a maximum weight, based on its power. The weight of all the train cars combined, including the engine, must be below this maximum weight or the engine will not be able to move the train. The following complete Engine class is used to represent the train’s engine.

Precondition: The maximum weight rating is greater than or equal to the weight of the Engine (every Engine object can pull itself).

Various train cars are represented by the TrainCar class. The weight of a TrainCar is its base weight plus the weight of its contents. The base weight of a TrainCar is the weight of the empty car. Many types of TrainCar objects exist, including passenger cars, boxcars, flatcars, cabooses, and so on. Each of these types has a different way of calculating the weight of its contents. Since each type of TrainCar does this differently, the getTotalWeight method is an abstract method.

(a)   TrainCar objects that are designed to transport people are called passenger cars and are represented by objects of the PassengerCar class. The weight of a PassengerCar is calculated by adding the base weight of the PassengerCar to the weight of the maximum number of people that the car can hold. The calculation assumes that the passenger car is filled to capacity and that each person, including luggage, weighs 300 pounds.

Write the complete PassengerCar class, including a constructor and any necessary instance variables and methods. The constructor takes as parameters the base weight of the car and the maximum number of passengers the car can hold. The class does not need to include a toString method or accessors and modifiers for any instance variables.

(b)   Trains are represented by the Train class and contain an Engine followed by any number of TrainCar objects. You may assume that the various classes that extend TrainCar have been correctly implemented and are not shown.

The weight of a Train object is calculated by adding the weight of the Engine to the weight of each of the TrainCar objects in the trainCars ArrayList . The Train class contains a removeExcessTrainCars method that ensures the engine is able to pull the train (to be completed in part (b)).

Trains need to be checked to make sure that their weight can be pulled by their Engine . If the train is overweight, train operators must remove train cars from the end of the train until the train is within the acceptable weight range.

Write the removeExcessTrainCars method of the Train class that removes TrainCar objects one at a time from the end of the train until the train is less than or equal to the maximum weight allowed as given by the getMaximumWeight method of the Engine object. The removed train cars are added to the end of an ArrayList of TrainCar objects as they are removed. This ArrayList of removed TrainCar objects is returned by the method. If no TrainCar objects need to be removed, an empty ArrayList is returned.

Example:

A train is composed of the cars listed below. The engine has a maximum weight rating of 475,000 pounds.

In the example, the train initially weighs 650,000 pounds. Train cars need to be removed one by one from the end of the train until the total weight is under the maximum allowed weight of 475,000.

  • Removing the train car from index 4 lowers the weight to 600,000
  • Removing the train car from index 3 lowers the weight to 500,000
  • Removing the train car from index 2 lowers the weight to 450,000

At 450,000 pounds, the train is now in the acceptable weight range. The following ArrayList is returned by the method:

Complete the removeExcessTrainCars method.

3 .    The colors of the pixels on a TV or computer screen are made by combining different quantities of red, green, and blue light. Each of the three colors is represented by a value between 0 and 255, where 0 means none of that color light and 255 means as much of that color as there can be. This way of representing colors is referred to as RGB, for red-green-blue, and the color values are written in ordered triples like this (80, 144, 240). That particular combination means red at a value of 80, green at a value of 144, and blue at a value of 240. The resulting color is a kind of medium blue. The combination (0, 0, 0) produces black and (255, 255, 255) produces white.

Pixels can be modeled by the Pixel class shown below.

An artist wants to manipulate the pixels on a large computer display. She begins by creating three two-dimensional arrays the size of the screen, rows by columns . One array contains the red value of each pixel, one contains the blue value of each pixel, and one contains the green value of each pixel. She then calls methods of the AlterImage class to generate and then manipulate the data.

(a)  Given the three arrays reds , greens and blues , and the Pixel and AlterImage classes, implement the generatePixelArray method that converts the raw information in the three color arrays into a rows by columns array of Pixel objects.

Precondition: The three color arrays are all the same size and contain int values in the range 0–255.

Postcondition: The returned array is the same size as the three color arrays.

(b)  The artist uses various techniques to modify the image displayed on the screen. One of these techniques is to flip the image, either horizontally (along the x -axis, top-to-bottom) or vertically (along the y -axis, left-to-right), so that a mirror image is produced as shown below.

In this example, the data in the cells are the RGB values stored in the Pixel objects. To make the example clearer, red is set to the original row number, green is set to the original column number, and blue is constant at 100.

Original array:

Flipped horizontally:

Flipped vertically:

Write the flipImage method, which takes as parameters a 2-D array of Pixel objects and a boolean direction to flip, where true means horizontally and false means vertically. The method returns the flipped image as a 2-D array of Pixel objects.

4 .    The classes below represent families, the people in them and the neighborhoods they live in.

Every individual member of a family is represented by the Person class.

(a)  Write the Person method matches . The method returns true if the values contained in the calling object’s name and age instance variables match the values contained in the passed object’s name and age instance variables.

(b)  The Family class models a family that consists of one or more adults and zero or more children. The instance variables for the Family class must include:

  • anArrayList to hold members of the family who are adults, where adult is defined to be age 18 and over, and
  • anArrayList to hold members of the family who are children.

There are two methods in the Family class:

  • theadd method that takes one parameter of type Person and adds it to the appropriate ArrayList , and
  • theisInFamily method that takes a Person object as a parameter and returns a boolean indicating whether that Person is a member of the object’s family.

Write the complete Family class.

You may assume that the matches method of the Person class works as intended, regardless of what you wrote in part (a). You must use it appropriately in order to receive full credit for part (b).

(c)  The Neighborhood class consists of a one or more Family objects, which are stored in an ArrayList .

Implement the isInNeighborhood method of the Neighborhood class.

You may assume that the Family class and its isInFamily method work as intended, regardless of what you wrote in part (b). You must use them appropriately in order to receive full credit for part (c).

STOP. End of Part II.

Practice Exam 1 Answers and Explanations

Part I Answers and Explanations (Multiple Choice)

Bullets mark each step in the process of arriving at the correct solution.

1 . The answer is E.

  • Lines 1 and 2 give us: myValue = 17 and multiplier = 3
  • Line 3: answer = 17 % 3 + 17 / 3

Using integer division: 17 / 3 = 5 remainder 2

  • 17 % 3 = 2
  • 17 / 3 = 5

The expression simplifies to answer = 2 + 5 = 7 (remember order of operations).

  • Line 4: answer = 7 * 3 = 21

2 . The answer is B.

  • Let’s use DeMorgan’s theorem to simplify the expression.
  • Distribute the first !. Remember to change|| to &&.
  • Distribute the second !.
  • It’s easy to simplify all those !s. Remember that !< >= and !<=  > (the same with > and >=).
  • Since these are all &&s, all four conditions must be true. The first condition says a >= b and the fourth condition says b < a. No problem there. Options B and C both have a > b.
  • The second condition says b > c. That’s true in option B.
  • The third condition says b < a. Still true in option B, so that’s the answer.
  • You could also solve this problem with guess and check by plugging in the given values, but all those ands and ors and nots tend to get pretty confusing. Simplifying at least a little will help, even if you are going to ultimately plug and play.

3 . The answer is D.

  • The while loop condition is (myArray[index] < 7). If you did not read carefully, you may have assumed that the condition was (index < 7), which, along with the index++ is the way you would write it if you wanted to access every element in the array.
  • Because the condition is (myArray[index] < 7), we will start at element 0 and continue until we come to an element that is greater than or equal to 7. At that point we will exit the loop and no more elements will be processed.
  • Every element before the 7 in the array will have 3 added to its value.

4 . The answer is A.

  • Option II uses a for-each loop. That is an excellent option for this problem, since we need to process each element in exactly the same way, but option II does not access the element correctly. Read the for-each loop like this: “For each OnlinePurchaseItem (which I will call purchase) in items. . . .” The variable purchase already holds the needed element. Using get(i) to get the element is unnecessary and there is no variable i.
  • Option III uses a for loop and processes the elements in reverse order. That is acceptable. Since we need to process every item, it doesn’t matter what order we do it in. However, option III starts at i = items.size(), which will cause anIndexOutOfBoundsException . Remember that the last element in an ArrayList is list.size() – 1 (just like a String or an array).
  • Option I correctly accesses and processes every element in the ArrayList.

5 . The answer is D.

  • This is a recursive method. Let’s trace the calls. The parts initalics were filled in on the way back up. That is, the calls in the plain type were written top to bottom until the base case returned a value. Then the answers were filled in bottom to top .
  • mystery(5) = 2 + mystery(4) = 2 +7 = 9 which gives us our final answer.
  • mystery(4) = 2 + mystery(3) = 2 +5 =7
  • mystery(3) = 2 + mystery(2) = 2 +3 =5
  • mystery(2) = 2 + mystery(1) = 2 +1 =3
  • mystery(1) Base Case! return 1

6 . The answer is E.

  • The outer loop will execute three times, starting at index = 0 and continuing as long as index < 4, increasing by one each time through. So index will equal 0, 1, 2, 3 in successive iterations through the loop.
  • The only statement inside the outer loop is the inner loop. Let’s look at what the inner loop does in general terms.
  • The inner loop executes from i = 0 to i < index, so it will execute index times.
  • Each time through it puts an "A" in front of and after myString.
  • Putting it all together:
  • The first iteration of the outer loop, index = 0, the inner loop executes 0 times, myString does not change.
  • The second iteration of the outer loop, index = 1, the inner loop executes one time, adding an "A" in front of and after myString. myString = "AHA"
  • The third iteration of the outer loop, index = 2, the inner loop executes two times adding two "A"s in front of and after myString. myString = "AAAHAAA"
  • The fourth (and last) iteration of the outer loop, index = 3, the inner loop executes three times, adding three more "A"s in front of and after myString. myString = "AAAAAAHAAAAAA"
  • Putting it another way, when index = 1, we add one "A"; when index = 2, we add two "A"s; when index = 3, we add three "A"s. That’s six "A"s all together added to the beginning and end of "H" "AAAAAAHAAAAAA"

7 . The answer is B.

  • The general form for generating a random number betweenhigh and low is:
  • high – low + 1 = 50, low = 10, so high = 59
  • The correct answer is integers between 10 and 59 inclusive.

8 . The answer is C.

  • This question requires that you understand the two uses of the + symbol.
  • First, we execute what is in the parentheses. Now we have:
  • Now do the addition left to right. That’s easy until we hit the string:
  • When you add a number and a string in any order, Java turns the number into a string and then concatenates the strings:
  • Now every operation we do will have a string and a number, so they all become string concatenations, not number additions.

"19APCS44"

9 . The answer is B.

  • This is a recursive method. Let’s trace the calls. The parts initalics were filled in on the way back up. That is, the calls in the plain type were written top to bottom until the base case returned a value. Then the answers were filled in bottom to top .
  • Be very careful to get the order of num1 and num2 correct in the modulus operation and the parameters correct in the recursive call.
  • guess(3, 17) = guess(17, 3) + 3 = 4 + 3 = 7 which gives us our final answer.
  • guess(17, 3) = guess(3, 2) + 2 = 2 + 2 = 4
  • guess(3, 2) = guess(2, 1) + 1 = 1 + 1 = 2
  • guess(2,1) Base case! return 3/2 = 1 (integer division)

10 . The answer is A.

  • myCar is instantiated as a reference variable pointing to an Automobile object with instance variables make = "Ford" and model = "Fusion".
  • companyCar is instantiated as a reference variable pointing to an Automobile object with instance variables make = "Toyota" and model = "Corolla".
  • The statement companyCar = myCar reassigns the companyCar reference variable to point to the same object as the myCar variable. They are now aliases of each other. The original companyCar object is now inaccessible (unless yet another variable we don’t know about points to it).
  • The next statement instantiates a brand-new Automobile object with make = "Kia" and model = "Spectre". It sets the myCar reference variable to point to this new object. This does not change the companyCar variable.
  • The companyCar variable still points to the object with instance variables make = "Ford" and model = "Fusion".
  • So we print companyCar’s make, which is "Ford" followed by myCar’s model, which is "Spectre".

11 . The answer is E.

  • Methods or constructors with the same name (and return type, in the case of methods) may have different parameter lists. The parameters may differ in type or number. This is calledoverloading .

12 . The answer is A.

  • We can eliminate options B and D immediately by noticing that active is a boolean and will therefore print as either "true" or "false" and not as "active" even though that is more informative.
  • We would expect option E to be correct by reading the code, but the constructor was called incorrectly. The overloaded constructor that is being called is the two-parameter constructor, and that constructor is going to assign its first parameter to state and its second parameter to city. Since we passed city, state, in that order, the city name and the state name have been assigned incorrectly and will therefore be printed incorrectly.
  • Note that this is a confusing way to write overloaded constructors! First, the order of the variables changes for no reason, and second, the names of the parameter are no help.

13 . The answer is D.

  • Option I is incorrect. Most classes have a no-argument constructor, either the default constructor provided automatically if no other constructor is provided, or one written by the programmer. However, the Depot class does not. The super call causes a compile time error.
  • Option II is correct. It implements a no-argument constructor in the WhistleStop class, which passes the needed parameters to the Depot constructor. It’s hard to imagine why you would want to default to constructing a station in the tiny town of Waubaushene, but if you want to do that, this code will do it for you.
  • Option III is also correct. It takes two parameters and correctly passes them to the Depot constructor via the call to super. However, this code will probably not give you the result you are expecting. Just like in question 12, the order of the city and province has been switched.

14 . The answer is A.

  • Option I is correct. The ArrayList is correctly instantiated as an ArrayList of Depot objects. Since a WhistleStop objectis-a Depot object, a WhistleStop object may be added to the ArrayList. WhistleStop contains a no-argument constructor, and the Depot constructor is called correctly as well.
  • Option II is incorrect. A WhistleStopis-a Depot, but not the other way around. We cannot put Depot objects into an ArrayList that is declared to hold WhistleStop objects. The ArrayList declaration will generate a compile-time error.
  • Option III is incorrect. The ArrayList is correctly instantiated as an ArrayList of WhistleStop objects. We can add WhistleStop objects to this ArrayList, but we cannot add Depot objects. The second add will generate a compile-time error.

15 . The answer is B.

  • When we start the for-each loop, the variable crazyString = "crazy" and the ArrayList crazyList has two elements ["weird," "enigma"].
  • You can read the for-each like this: “For each String (which I am going to call s) in crazyList. . . .”
  • So for each String s in crazyList we execute the assignment statement:

which takes two characters starting at index 1 from s and concatenates the first four characters of crazyString.

  • The first time through the loop, s = "weird" and crazyString = "crazy" so the assignment becomes:

Remember that substring starts at the first parameter and ends before the second parameter, and remember that we start counting the first letter at 0.

  • The second time through the loop, s = "enigma" and crazyString = "eicraz" so the assignment becomes:

16 . The answer is E.

  • There are four possible paths through the code. We need one data element that will pass through each path.
  • The first path is executed if n < −5.
  • The second path is executed if -5  n < 0 (because if n < −5, the first path is executed and we will not reach the second path).
  • The third path is executed if n > 10.
  • The fourth path is executed in all other cases.
  • We need to be sure that we have at least one piece of data for all four of those cases.
  • Option A does not test the fourth path, because 12 and 15 are both > 10.
  • Option B does not test the first path, because it doesn’t have a number that is < −5.
  • Option C does not test the third path, because it doesn’t have a number that is > 10.
  • Option D does not test the second path, because 0 is not less than 0.
  • Option E tests all four paths.

17 . The answer is C.

  • This statement should be written with cascading if-else clauses. When the clause associated with a true condition is executed, the rest of the statements should be skipped. Unfortunately, that is not how it is written. For example, if the parameter temp = 80, the first if is evaluated and found to be true and activity = "go swimming"; however, since there is no else, the second if is also evaluated and found to be true, so activity = "go hiking". Then the third if is evaluated and found to be true, so activity = "go horseback riding". The else clause is skipped and "go horseback riding" is returned (incorrectly).
  • All temperatures that are true for multiple if statements will cause activity to be set incorrectly. Only the values of temp that will execute the last if or the else clause will return the correct answer.
  • In order for this code to function as intended, all ifs except the first one should be preceded withelse .

18 . The answer is D.

  • This time, there are if-else clauses, but they are in the wrong order. It is important to write the most restrictive case first. Let’s test this code by using 80 degrees as an example. 80 > 75, and that is the condition we intend to execute, but unfortunately, it is also > 45, which is the first condition in the code, so that is the if clause that is executed and activity is set to "go horseback riding". Since the code is written as a cascading if-else, no more conditions are evaluated and flow of control jumps to the return statement.
  • Two sets of values give the right answer:
  • Values that execute the first if clause correctly—that is, values that are greater than 45, but less than or equal to 60.
  • Values that fail all the if conditions and execute the else clause—that is, values that are less than or equal to 45.
  • Those two conditions can be combined into temperatures <=60.
  • In order for this code to function as intended, the order of the conditions needs to be reversed.

19 . The answer is A.

  • Let’s look at the three code segments one by one.
  • Option I:
  • When we enter the loop, i = 1.
  • arr[1 / 2] = arr[0] = 1 (don’t forget integer division)
  • i = i + 2 = 3, 3 < 6 so we enter the loop again.
  • arr [3 / 2] = arr[1] = 3
  • i = i + 2 = 5, 5 < 6 so we enter the loop again.
  • arr[5 / 2] = arr[2] = 5
  • i = i + 2 = 7, 7 is not < 6 so we exit the loop.
  • The array arr = [1, 3, 5]
  • Option II:
  • When we enter the loop, i = 0.
  • arr[0] = 2 * 0 + 1 = 1
  • increment i to 1, 1 < 3 so we enter the loop again.
  • arr[1] = 2 * 1 + 1 = 3
  • increment i to 2, 2 < 3 so we enter the loop again.
  • arr[2] = 2 * 2 + 1 = 5
  • increment i to 3, 3 is not < 3 so we exit the loop.
  • The array arr = [1, 3, 5]
  • Option III:
  • When we enter the loop, i = 6.
  • arr[(6 – 6) / 2] = arr[0] = 6 – 6 = 0
  • Since we know the first element should be 1, not 0, we can stop here and eliminate this option.
  • Options I and II produce the same results.

20 . The answer is C.

  • Let’s picture our ArrayList as a table. After the add statements, ArrayList nations looks like this:
  • It looks like perhaps the loop is intended to remove all elements whose length is greater than or equal to 7, but that is not what this loop does. Let’s walk through it.
  • i = 0. nations.size() = 6, 0 < 6 so we enter the loop.
  • nations.get(0).length() gives us the length of "Argentina" = 9.
  • 9 >= 7, so we remove the element at location 0. Now our ArrayList looks like this:
  • increment i to 1. nations.size() = 5, 1 < 5, so we enter the loop.
  • nations.get(1).length() gives us the length of "Australia" = 9. (We skipped over "Canada" because it moved into position 0 when "Argentina" was removed.)
  • 9 >= 7, so we remove the element at location 0. Now our ArrayList looks like this:
  • increment i to 2. nations.size() = 4, 2 < 4 so we enter the loop.
  • nations.get(2).length() gives us the length of "Russia" = 6.
  • 6 is not >= 7 so we skip the if clause.
  • increment i to 3. nations.size() = 4, 3 < 4 so we enter the loop.
  • nations.get(3).length() gives us the length of "France" = 6.
  • 6 is not >= 7 so we skip the if clause.
  • increment i to 4. nations.size() = 4, 4 is not < 4 so we exit the loop with the ArrayList:
  • Note: You have to be really careful when you remove items from an ArrayList in the context of a loop. Keep in mind that when you remove an item, the items with higher indices don’t stay put. They all shift over one, changing their indices. If you just keep counting up, you will skip items. Also, unlike an array, the size of the ArrayList will change as you delete items.

21 . The answer is C.

  • doStuff is going to loop through the array, checking to see if each item is the same as the item before it. If it is, the values of index, value, and counter all change. If it is not, only counter changes.
  • Begin by setting index = 0; value = 1; counter = 1; and noting that numberArray.length() = 5.
  • First iteration: k = 1, enter the loop with index = 0; value = 1; counter = 1;
  • Item 1 = item 0, execute the if clause
  • counter <= value, execute the if clause
  • value = 1; index = 1
  • counter = 2
  • Second iteration: k = 2, enter the loop with index = 1; value = 1; counter = 2;
  • Item 2 != item 1, execute the else clause
  • counter = 1
  • Third iteration: k = 3, enter the loop with index = 1; value = 1; counter = 1;
  • Item 3 = item 2, execute the if clause
  • counter <= value, execute the if clause
  • value = 1; index = 3
  • counter = 2
  • Fourth iteration: k = 4, enter the loop with index = 3; value = 1; counter = 2;
  • Item 4 != item 3, execute the else clause
  • counter = 1
  • Fifth iteration: k = 5, which fails the condition and the loop exits.
  • index = 3, numberArray[3] = 4 is returned and printed.

22 . The answer is D.

  • This question is explained along with question 23 below.

23 . The answer is D.

  • We will solve questions 22 and 23 together by diagramming the objects and reference variables.
  • The first three assignment statements give us:
  • c3.setX(c2.getY());results in:
  • c3 = c2;results in:
  • c3.setY(c2.getX());results in:
  • c2.setX(c1.getX());results in:
  • Question 22: Both c2.getY() and c3.getY() return 20, but only c2.getY() is an option.
  • Question 23: c1.getX(), c2.getX(), and c3.getX() all return 30.

24 . The answer is B.

  • Youimplement an interface and extend a class.
  • Supernatural is an interface, so it must be implemented.
  • Werewolf is a class, so it must be extended.

25 . The answer is E.

  • You may implement as many interfaces as you like, but you can extend only one class.

26 . The answer is C.

  • Option A is incorrect. If Child extended Adult, this would be the correct constructor, but Child extends Person. The Person constructor does not take a title, only a first name and last name.
  • Option B is incorrect because Person does not have a no-argument constructor. The call to super() will cause a compile time error.
  • Options D and E are incorrect because of the “extends” phrase. The keywordextends is used in the class declaration, not the constructor declaration.
  • Option C is the only correctly written constructor.

27 . The answer is E.

  • Options A and D are incorrect because they print information to the console rather than returning it as a string. Option A also calls super.toString, which does not exist.
  • Option B is incorrect because, like option A, it calls super.toString, which does not exist.
  • Option C is incorrect because firstName and lastName are private instance variables of the Person class and cannot be accessed by the Adult class.
  • Option E is a correctly written toString method.

28 . The answer is C.

  • Method findSomeone is expecting a parameter of type Adult. The question is, which of the options correctly provides a parameter of type Adult?
  • Option I is incorrect. Here, the parameter is of type Person. Adult extends Person, not the other way around, so a Person is not an Adult.
  • Option II is correct. The parameter is of type Adult.
  • Option III is incorrect. Here, the parameter is of type Child. Child extends Person, not Adult, so a Child is not an Adult.
  • Option IV is correct. A Person reference variable can be downcast to an Adult since Adult extends Person. At run-time, if the reference variable does not reference an Adult object as promised by the cast, the program will crash with a run-time error.
  • Option V is incorrect. Child is not a superclass of Adult. Child cannot be downcast to Adult.

29 . The answer is E.

  • The basic formula for tolerance is:
  • In our case, a is valpower, or Math.pow(val, power), and b is target, so the equation becomes:
  • That evaluates to a boolean. We could assign it to a boolean variable and return the variable, but we can also just return the expression as in option E.

30 . The answer is C.

  • This problem requires you to understand that primitives are passed by value and objects are passed by reference.
  • When a primitive argument (or actual parameter) is passed to a method, its value is copied into the formal parameter. Changing the formal parameter inside the method has no effect on the value of the variable passed in. The caller’s num1 will not be changed by the method.
  • The caller’s num2 is not changed when the num2++ is executed inside the method. That new value, however, is returned by the method, and the caller uses the returned value to reset num2. The value of num2 will change.
  • When an object is passed to a method, its reference is copied into the formal parameter. The actual and formal parameters become aliases of each other; that is, they both point to the same object. Therefore, when the object is changed inside the method, those changes will be seen outside of the method. Changes to array values inside the method will be seen in array values outside of the method.
  • num1 remains equal to 2, even though the method’s num1 variable is changed to 4. num2 is reset to 4, because the method returns that value, and values[4] is set to 3.

31 . The answer is B.

  • To convert from decimal to hexadecimal (base 16), we need to remember the place values for base 16. A base 16 number has the 1’s place on the right (like every base), preceded by the 16’s place.
  • Our first number is 125. How many times does 16 go into 125? 16 * 7 = 112. So we have a 7 in the 16’s place. 125 – 112 = 13, so we have 13 left. We need to put 13 in the 1’s place. That’s D in hex. So our answer is 7D.
  • Our second number is 200. Following the same procedure, 16 * 12 = 192. We want to put a 12 in the 16’s place. That’s C in hex. 200 – 192 = 8, so our number is C8.
  • Our third number is 78. 16 * 4 = 64. Put a 4 in the 16’s place. 78 – 64 = 14. That’s E in hex. Our number is 4E.
  • Putting the three hex values together in order, we get #7DC84E.

32 . The answer is C.

  • First split the hexadecimal number into its three components: EA, 27, B5.
  • Consider EA. The E is in the 16’s place. E is 14, so we have 14 * 16 = 224. A is 10, in the 1’s place, so our first answer is 234.
  • Consider 27. 2 * 16 = 32. 32 + 7 = 39.
  • Last B5. B is 11. 11 * 16 = 176. 176 + 5 = 181
  • Our ordered triple is (234, 39, 181).

33 . The answer is A.

  • The Binary Search algorithm should not be applied to this array! Binary Search only works on a sorted array. However, the algorithm will run; it just won’t return reasonable results. Let’s take a look at what it will do.
  • First look at the middle element. That’s 100. 50 < 100, so eliminate the second half of the array.
  • Look at the middle element of the remaining part; 50 < 11, so eliminate the lower half.
  • 50 does not appear in the remaining elements, return -1 (incorrectly, as it turns out).

34 . The answer is C.

  • After the array is instantiated, it looks like this:
  • The for loop will execute three times: x = 0, x = 1, and x = 2.
  • You should recognize that the code in the loop is a simple swap algorithm that swaps the value at nums[x][0] with the value at nums[x][2].
  • The result is that in each row, element 0 and element 2 will be swapped.
  • Our final answer is:

35 . The answer is A.

  • Let’s trace the loop and see what happens. On entry we have:
  • i = 1. In pseudocode, the if statement says "if (element 1 of list > the last element in newList) add it to newList" Since 4 > 2, add 4 to newList, which becomes:
  • i = 2. "if (element 2 of list > the last element in newList) add it to newList" 3 is not > 4 so we do not add it.
  • i = 3. "if (element 3 of list > the last element in newList) add it to newList" 3 is not > 4, we do not add it. (By this point, you may recognize what the code is doing and you may be able to complete newList without tracing the remaining iterations of the loop.)
  • i = 4 "if (element 4 of list > the last element in newList) add it to newList" 2 is not > 4, we do not add it.
  • i = 5. “if (element 5 of list > the last element in newList) add it to newList" 5 > 4, add 5 to newList which becomes:
  • i = 6. "if (element 6 of list > the last element in newList) add it to newList" 1 is not > 5, so we do not add it.
  • We have completed the loop; we exit and print newList.

36 . The answer is E.

  • After the array is instantiated, it is filled with 0s because that is the default value for an int, so anything we don’t overwrite will be a 0.
  • Let’s look at the first loop. r goes from 0 to 4, so all rows are affected. c starts at r+1 and goes to 4, so not all columns are affected. When r = 0, c will = 1,2,3,4; when r = 1, c will = 2,3,4; when r = 2, c will = 3,4; when r = 3, c will = 4. That will assign 9 to the upper right corner of the grid like this.
  • In the second loop, d goes from 0 to 4, so all rows are affected, and c always equals r, so the diagonals are filled in with their row/column number.
  • Now we just have to look for the three cells specified in the problem.

37 . The answer is D.

  • The first thing to do is to identify the sorting algorithm implemented by mysterySort.
  • We can tell it’s not Merge Sort, because it is not recursive.
  • There are several things we can look for to identify whether a sort is Insertion Sort or Selection Sort. Some easy things to look for:
  • In the inner loop, Insertion Sort shifts items over one slot.
  • After the loops are complete, Selection Sort swaps two elements.
  • We can see items being shifted over and we can’t see a swap, so this is Insertion Sort.
  • Let’s look at the state of the array in table form. Before the sort begins, we have this. The sort starts by saying that 9 (all by itself) is already sorted.
  • The first iteration through the loop puts the first two elements in sorted order.
  • The second iteration through the loop puts the first three elements in sorted order.
  • Notice that in Insertion Sort, the elements at the end of the array are never touched until it is their turn to be “inserted.” Selection Sort will change elements all through the array.

38 . The answer is C.

  • This is a recursive method. Let’s trace the calls. The parts initalics were filled in on the way back up. That is, the calls in the plain type were written top to bottom until the base case returned a value. Then the answers were filled in bottom to top .
  • puzzle (3, 4) = 3 * puzzle (3, 3) = 3 * 27 = 81 which gives us our final answer
  • puzzle (3, 3) = 3 * puzzle (3, 2) = 3 * 9 = 27
  • puzzle (3, 2) = 3 * puzzle (3, 1) = 3 * 3 = 9
  • puzzle (3, 1) Base Case! return 3
  • It is interesting to notice that this recursive method finds the first parameter raised to the power of the second parameter.

39 . The answer is D.

  • This nested for loop is traversing the array in column major order. I can tell this is the case because the outer loop, the one that is changing more slowly, is controlling the column variable. For every time the column variable changes, the row variable goes through the entire row.
  • In addition, although the outer loop is traversing the columns from least to greatest, the inner loop is working backward through the rows.
  • Since we increase val by 2 each time, values are being filled in like this:
  • You probably didn’t need to fill in the whole table to figure out that table[3][4] = 42.

40 . The answer is E.

  • Since this is a Selection Sort algorithm, we know that the inner loop is looking for the smallest element.
  • small is storing the index of the smallest element we have found so far. We need to find out if the current element being examined is smaller than the element at index small, or, in other words, if arr[j] is less than arr[small].
  • Option C would be correct if we were sorting an array of ints, but < doesn’t work with strings. We have to use the method compareTo. compareTo returns a negative value if the calling element is before the parameter value. We need:

Part II Solutions (Free Response)

Please keep in mind that there are multiple ways to write the solution to a free-response question, but the general and refined statements of the problem should be pretty much the same for everyone. Look at the algorithms and coded solutions, and determine if yours accomplishes the same task.

General Penalties (assessed only once per problem):

-1   using a local variable without first declaring it

-1   returning a value from a void method or constructor

-1   accessing an array or ArrayList incorrectly

-1   overwriting information passed as a parameter

-1   including unnecessary code that causes a side effect such as a compile error or console output

1 .   Regular Hexagon

(a)  General Problem: Write the getSideLength method for the RegularHexagon class.

Refined Problem: Use the distance formula to compute and return the length of one side of a regular hexagon. Use any two consecutive entries in ArrayList points. Access the x and y values by using the methods in the CoordinatePoint class.

Algorithm:

  • Get the x coordinate of element 0 in the ArrayList points.
  • Get the y coordinate of element 0 in the ArrayList points.
  • Get the x coordinate of element 1 in the ArrayList points.
  • Get the y coordinate of element 1 in the ArrayList points.
  • Compute the distance between the two points, using the Math class methods pow and sqrt. Be careful to place parentheses accurately.
  • Return the computed value.

Java Code:

Common Errors:

  • Be careful whenever you transcribe a formula. Check each parenthesis placement carefully. It’s a good idea to count the open parentheses and the close parentheses to make sure you have the same number.

Java Code Alternate Solution #1:

You can skip storing the values in variables, though it makes the return statement pretty complex. You could also have stored the answer in a variable and returned that variable.

Java Code Alternate Solution #2:

You can use multiplication instead of Math.pow.

 

(b) General Problem: Write the getArea method for the RegularHexagon class.

Refined Problem: Use the area formula given in the problem to compute and return the area of the hexagon. Get the side length by using the method written in part (a).

Algorithm:

  • Compute the area using the value returned by the sideLength method, and the Math class methods pow and sqrt. Be careful to place parentheses accurately.
  • Return the computed value.

Java Code:

 

(c) General Problem: Write the getCenter method for the RegularHexagon class.

Refined Problem: Use the accessor methods of the CoordinatePoint class to get the x and y values from elements that define a diagonal. Use the midpoint formula given in the problem to compute the point at the center of the hexagon. Create and return a CoordinatePoint object containing the center point.

Algorithm:

  • Get the x coordinate of element 0 in the ArrayList points.
  • Get the y coordinate of element 0 in the ArrayList points.
  • Get the x coordinate of element 3 in the ArrayList points.
  • Get the y coordinate of element 3 in the ArrayList points.
  • Compute the x and y values of the midpoint of the two points.
  • Create a new CoordinatePoint object with the calculated x and y points.
  • Return the CoordinatePoint object.

Java Code:

Common Errors:

  • Remember to put (x1 + x2) in parentheses. Otherwise, order of operations will yield x1 + (x2 / 2).

Java Code Alternate Solution:

  • Like 1a, none of the variables are required. Sometimes a happy medium is a better solution than either of these examples.

Scoring Guidelines: Regular Hexagon

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from our sample solutions and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works, and will help you debug it if it does not.

Copy RegularHexagonDriver into your IDE along with the complete RegularHexagon and CoordinatePoint classes (including your solutions). You will also need to add this import statement as the first line in your RegularHexagon class: import java.util.ArrayList;

2 .    Train

(a)  General Problem: Complete the PassengerCar class, which extends the TrainCar abstract class.

Refined Problem: The PassengerCar class should include the necessary instance variables, a properly written constructor, and all the methods required by the TrainCar abstract class.

Algorithm:

  • Use "extends TrainCar" in the class declaration.
  • Create an instance variable to hold maxPassengers.
  • Write a constructor that takes the car’s baseWeight and its maxPassengers as parameters, calls super, passing the baseWeight, and sets the maxPassengers instance variable.
  • Write the required getTotalWeight method, which returns the baseWeight (from the super class) + 300 * maxPassengers. Declare 300 as a constant so there are no magic numbers in the code (not required, but good programming style).

Java Code:

Common Errors:

  • The first statement in the constructor needs to be super(baseWeight). Remember that the call to super must come first.

(b)  General Problem: Write the removeExcessTrainCars method of the Train class that removes cars from the train until the train is light enough to be pulled by the engine.

Refined Problem: Calculate the initial weight of the train. If the weight exceeds the weight limit, TrainCars are removed from the end of the train until the weight is in the acceptable range. All train cars that are removed are returned in an ArrayList in the order they are removed from the train.

Algorithm:

  • Create an ArrayList of TrainCars to hold the removed cars.
  • Create a variable to hold the total weight of the train.
  • Calculate the weight of the train by adding the weight of the Engine with the weights of all the TrainCar objects in trainCars.
  • While the total weight is greater than the Engine’s maximum weight,
  • Remove a train car from the end of the train
  • Add it to the ArrayList to be returned
  • Subtract its weight from the total weight of the train
  • Return the ArrayList of removed cars (which may be empty).

Java Code:

Common Errors:

  • This method must be done in two consecutive loops. You have to know the total weight before you can start removing cars.
  • Remember that remove also returns the removed element. You do not need a get followed by a remove.

Java Code Alternate Solution:

  • The first loop that calculates the weight of the entire train can be written as a for loop.
  • The second loop calculations can be written without a temp holding variable.

Scoring Guidelines: Train

3 . Pixels

(a)  General Problem: Write the generatePixelArray method to convert three 2-D int arrays into a 2-D array of Pixel objects.

Refined Problem: Use a nested for loop to instantiate a Pixel object for each element of the Pixel object array. Use the corresponding values in the red, green, and blue arrays as parameters to the Pixel constructor. When the loops are complete, return the completed array.

Algorithm:

  • Create a 2-D array of type Pixel to hold the new Pixel objects. The dimensions of this array are the same as any of the color arrays because there is a precondition saying all the arrays must be the same size.
  • Write a for loop that goes through all the rows of the new array.
  • Nested in that for loop, write a for loop that goes through all the columns of the new array. (These can be switched. Row-major order is more common, but column-major order will also work here.)
  • Instantiate a new Pixel object, passing the values in the red, green, and blue arrays at the position given by the two loop counters, and assign it to the element of the Pixel array given by the two loop counters.
  • When the loops are complete and every element has been processed, return the completed Pixel array.

Java Code:

(b)  General Problem: Write a flipImage method that takes a 2-D array of Pixel objects and flips it into a mirror image, either vertically or horizontally.

Refined Problem: Create a new array to hold the altered image. Determine whether to flip the image horizontally or vertically. Write a nested for loop to move all the Pixels to their mirror-image location in the new array, either horizontally or vertically. When the loops are complete, return the new array.

Algorithm:

  • Instantiate a 2-D Pixel array that has the same dimensions as the array passed as a parameter. This array will hold the altered image.
  • Create an if-else statement with one clause for a horizontal flip and one for a vertical flip.
  • If the flip is horizontal, write a nested for loop that goes through the array in row-major order.
  • For each iteration of the loop, an entire row is moved into its new "flipped" place in the altered array.
  • Otherwise, the flip is vertical. Write a nested for loop that goes through the array in column-major order.
  • For each iteration of the loop, an entire column is moved into its new "flipped" place in the altered array.
  • Return the altered array.

Java Code:

Common Errors:

  • Watch off-by-one errors. Always think: do I want length or length – 1? Using variables, like in the alternate solution, can help you be consistent.
  • Be sure you understand the difference between row-major and column-major order.
  • Check your answer with both even and odd numbers of rows and columns.
  • Create a new array to hold the “flipped” version. Do not overwrite the array that is passed in. This is calleddestruction of persistent data and incurs a penalty.

Java Code Alternate Solution:

  • This solution only loops halfway through the array. It flips a pair lines on each iteration.

This solution also uses a few extra variables to keep things easier to read. This is not necessary but it reduces the amount of typing and the chance of an off-by-one error with length, as opposed to length – 1.

Scoring Guidelines: Pixels

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from our sample solutions and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works, and will help you debug it if it does not.

Copy PixelDriver and the complete Pixel class into your IDE. Add your generatePixelArray and flipImage methods to the bottom of the PixelDriver class.

4 .    Families

(a)  General Problem: Write a matches method for the Person class.

Refined Problem: Write a matches method that compares the name and age of the Person object passed as a parameter with this object and returns true if they are the same and false if they are different.

Algorithm:

  • Write an if statement with two conditions: this object’s name is the same as parameter object’s name and this object’s age is the same as parameter object’s age. Be sure to use == to compare int variables and the equals method to compare String variables.
  • If both conditions are true, return true.
  • Otherwise, return false.

Java Code:

Java Code Alternate Solution:

  • This solution uses methods instead of directly accessing the instance data. It also usesthis to refer to the object itself. The use of this is optional. However, comparing this object to a parameter object can be confusing, and having an object name for both sides of the equals can help. Lastly, this solution uses the completely optional else .

(b) General Problem: Write the entire Family class.

Refined Problem: Write the Family class. It will have two instance variables: an ArrayList of Person objects to hold the adults in the family and an ArrayList of Person objects to hold the children in the family. There will also be two methods: an add method that adds a new Person object to the correct ArrayList based on age, and an isInFamily method that determines if a Person passed as a parameter is in either of the ArrayLists, and is therefore a member of the family.

Algorithm:

  • Write the class declaration.
  • Instantiate the two ArrayLists of Person objects, one called adults and one called children.
  • Write the add method. It must check the age of the Person object passed as a parameter. If it is greater than or equal to 18, add the Person object to the adults ArrayList; if it is less than 18, add the Person object to the children ArrayList.
  • Write the isInFamily method. Traverse both ArrayLists looking for a Person object that equals the Person object passed as a parameter. If one is found, immediately return true. If no match is found after traversing both ArrayLists, return false. Be sure to use the matches method of the Person class written in part (a) to compare the Person objects.

Java Code:

Common Errors:

There are several opportunities for error in the isInFamily method.

  • Sometimes people begin with boolean found = false and then set it to true if the person is found. That’s a perfectly fine approach provided no subsequent code will ever set it back to false. It is a common error to flip-flop that boolean depending on whether the current search finds the person, and obviously that does not work.
  • The return false must be outside of the loops. You can return true immediately when the person is found, but you cannot return false until you have checked every person in every ArrayList.
  • Make sure you use the matches method written in part (a). Do not rewrite the code here.

Java Code Alternate Solution:

The isInFamily method can be written with for loops instead of for-each loops.

(c)  General Problem: Write the isInNeighborhood method of the Neighborhood class.

Refined Problem: Write method isInNeighborhood, which takes a Person object as a parameter and determines if that Person object appears in any of the families in the ArrayList of Family objects.

Algorithm:

  • Traverse the ArrayList<Family> families.
  • Use the isInFamily method of the Family class to determine if the Person object passed as a parameter is a member of the Family object. Be sure to use the method written in part (b).
  • If the Person object is found in a Family, return true.
  • If the traversal completes without locating the Person in a Family, return false.

Java Code:

Common Errors:

  • Like in part (b), you can return true (or set a boolean) as soon as you find one true response, but you cannot return false until everything has been checked. The return false must be outside the loop.
  • Be sure to use the isInFamily method.

Java Code Alternate Solution:

This solution uses a for loop instead of a for-each loop.

Scoring Guidelines: Families

Scoring Worksheet

This worksheet will help you to approximate your performance on Practice Exam 1 in terms of an AP score of 1–5.

Part I (Multiple Choice)

Part II (Short Answer)

See the scoring guidelines included with the explanations for each of the questions and award yourself points based on those guidelines.

Approximate conversion from raw score to AP score







All materials on the site are licensed Creative Commons Attribution-Sharealike 3.0 Unported CC BY-SA 3.0 & GNU Free Documentation License (GFDL)

If you are the copyright holder of any material contained on our site and intend to remove it, please contact our site administrator for approval.

© 2016-2024 All site design rights belong to S.Y.A.