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

STEP 5

Building Your Test-Taking Confidence

AP Computer Science A: Practice Exam 2

Multiple-Choice Questions

ANSWER SHEET

AP Computer Science A: Practice Exam 2

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?

2 .   Consider the following code segment.

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

(A)  [Salad, Empanadas, Sushi, Curry]

(B)  [Hummus, Salad, Empanadas, Sushi, Curry]

(C)  [Hummus, Soup, Sushi, Empanadas, Salad, Curry]

(D)  [Soup, Empanadas, Sushi, Curry]

(E)  [Hummus, Sushi, Salad, Curry]

3 .   Consider the following output.

Which of the following code segments will produce this output?

III.  

(A)  I only

(B)  II only

(C)  I and II only

(D)  II and III only

(E)  I, II, and III

Questions 4–5 refer to the following two classes.

4 .   Assume the following declaration appears in a client program.

What is printed as a result of executing the call yacht.start() ?

(A)  Vroom

(B)  Remaining Fuel 18

(C)  Remaining Fuel 20

(D)  Vroom

       Remaining Fuel 18

(E)  Vroom

       Remaining Fuel 20

5 .   Which of the following statements results in a compile-time error?

  1. Boat sailboat = new Boat(2);
  2. Vehicle tanker = new Boat(20);

III.  Vehicle car = new Vehicle(10);

(A)  I only

(B)  II only

(C)  III only

(D)  II and III only

(E)  None of these options will result in a compile-time error.

6 .   Consider the following recursive method.

What value is returned as a result of the call weird(3) ?

(A)  -2

(B)  3

(C)  4

(D)  6

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

7 .   Consider the following method.

The method verifyValues is intended to return true if the array passed as a parameter is in ascending order (least to greatest), and false otherwise.

Which of the following lines of code could replace /* missing code */ so the method works as intended?

(A)  if (values[index] <= values[index - 1])

(B)  if (values[index + 1] < values[index])

(C)  if (values[index] >= values[index – 1])

(D)  if (values[index - 1] > values[index])

(E)  if (values[index] < values[index + 1])

8 .   Consider the following code segment.

What is the value of sum after the code segment has been executed?

(A)  0

(B)  9

(C)  21

(D)  36

(E)  72

9 . Consider the following class used to represent a student.

Consider the ExchangeStudent class that extends the Student class.

Which of the following constructors could also be included in the ExchangeStudent class without generating a compile-time error?

III.  

(A)  I only

(B)  II only

(C)  III only

(D)  I and III only

(E)  I, II, and III

10 .    Consider the following code segment.

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

(A)  0

(B)  1

(C)  1073741823

(D)  Nothing will be printed. The code segment will terminate without error.

(E)  Nothing will be printed. The first loop is an infinite loop.

11 .    Consider the following method.

Assume that the ArrayList passed as a parameter contains the following Integer values.

What value is returned by the call totalValue ?

(A)  20

(B)  21

(C)  27

(D)  44

(E)  45

Questions 12–13 refer to the following interface and class definitions, which are components of a video game.

A PlayerShip object is controlled by the human player.

An EnemyShip object is controlled by the computer.

12 .    An EnemyShip object has the following behavior:

  • AnEnemyShip always moves from right to left in the x direction by subtracting 1 from the xPosition for each move. When xPosition reaches 0 , it is reset to 1000.
  • AnEnemyShip always moves toward a PlayerShip in the y direction, or stays in its current y position if the PlayerShip and the EnemyShip have the same yPosition (since the EnemyShip cannot get any closer).

Given PlayerShip player, which of the following is a correct implementation of the move method in the Enemyship class?

III.  

(A)  I only

(B)  II only

(C)  III only

(D)  I and II only

(E)  II and III only

13 .    Which of the following classes correctly implements the Ship interface?

III.  

(A)  I only

(B)  II only

(C)  III only

(D)  I and II only

(E)  II and III only

14 .    A bank will approve a loan for any customer who fulfills one or more of the following requirements:

  • Has a credit score ≥ 640
  • Has a cosigner for the loan
  • Has a credit score ≥ 590 and has collateral

Which of the following methods will properly evaluate the customer’s eligibility for a loan?

III.  

(A)  I only

(B)  II only

(C)  III only

(D)  I and III only

(E)  II and III only

15 .    Consider the following code segment.

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

(A)  0

(B)  1

(C)  8

(D)  33

(E)  Nothing will be printed. It is an infinite loop.

16 .    Assume that planets has been correctly instantiated and initialized to contain the names of the planets. Which of the following code segments will reverse the order of the elements in planets ?

(A)  

(B)  

(C)  

(D)  

(E)  

17 .    When designing a class hierarchy, what should be true of an abstract class?

(A)  An abstract class should contain the methods and class variables that all of its subclasses have in common, even if the correct implementations of the methods are unknown.

(B)  An abstract class must be the largest most complicated superclass for which all other classes should derive.

(C)  An abstract class should contain all final variables and static methods of the hierarchy.

(D)  An abstract class should contain the specific implementations of every method inherited from an interface that the abstract class implements.

(E)  An abstract class should contain basic implementation of all methods so that subclasses can override its implementation with more specific and correct methods.

18 .    Consider the following code segment.

What are the possible values that could be printed to the console?

(A)  All real numbers from 4 to 10 (not including 10)

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

(C)  All integers from 20 to 49 (inclusive)

(D)  All integers from 25 to 54 (inclusive)

(E)  All real numbers from 30 to 50 (inclusive)

19 .    Consider the following code segment.

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

(A)  [computer, mputer, uter, er]

(B)  [computer, comput, comp, co]

(C)  [computer, computer, computer, computer]

(D)  [computer, omputer, mputer, puter, uter, ter, er, r]

(E)  Nothing is printed. There is an ArrayListIndexOutOfBoundsException .

20 .    Consider the following incomplete method.

The following table shows several examples of the desired result of a call to validation .

Which of the following code segments should replace /* missing code */ to produce the desired return values?

(A)  return x > y;

(B)  return (x % y) > 1

(C)  return (x + y) % 2 == 0

(D)  return (x + y) % x == y;

(E)  return (x + y) % 2 > (y + y) % 2;

21 .    Consider the following method that is intended to remove all Strings from words that are less than six letters long.

Which line of code contains an error that prevents letterCountCheck from working as intended?

(A)  Line 1

(B)  Line 2

(C)  Line 3

(D)  Line 4

(E)  Line 5

22 .    Consider the following recursive method.

What is printed as a result of executing the call wackyOutput("APCS") ?

(A)  PC

(B)  SCPA

(C)  SCSPCS

(D)  PCSCSS

(E)  SCSPCSAPCS

23 .    Consider the following method.

Which of the following methods will give the exact same results as calculate ?

 III.  

(A)  I only

(B)  II only

(C)  III only

(D)  I and II only

(E)  I, II, and III

24 .    Consider the following class declaration.

The following code segment is executed in the main method.

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

(A)  0.0

(B)  3.0

(C)  12.0

(D)  19.0

(E)  27.5

25 .    Assume truth1 and truth2 are boolean variables that have been properly declared and initialized.

Consider this expression.

Which expression below is its logical equivalent?

(A)  truth1 != truth2

(B)  truth1 || truth2

(C)  truth1 && truth2

(D)  !truth1 && !truth2

(E)  truth1 == truth2

26 .    The following insertion sort method sorts the array in increasing order. This method includes an additional System.out.print(value + " ") statement that is not normally included in the insertion sort.

Consider the following array.

What is printed as a result of executing the call sortIt(costs) ?

(A)  3.1 7.8 1.4 6.6 5.2

(B)  3.1 7.8 1.4 6.6 5.2 9.1

(C)  2.6 3.1 7.8 1.4 6.6 5.2 9.1

(D)  1.4 2.6 3.1 5.2 6.6 7.8 9.1

(E)  3.1 3.1 7.8 7.8 1.4 1.4 6.6 6.6 5.2 5.2 9.1 9.1

27 .    Consider the following interface.

Consider the following class.

Which of the following is a correct implementation of the contains method?

(A)  

(B)  

(C)  

(D)  

(E)  

28 .    Consider the following method.

Assume that ArrayList<String> list has been correctly instantiated and populated with the following entries.

What are the values of the ArrayList returned by the call rearrange(list) ?

(A)  ["Silja", "Garrett", "Nate", "Madeline", "Charles", "Nora"]

(B)  ["Madeline", "Charles", "Nora", "Nate", "Silja", "Garrett"]

(C)  ["Nate", "Silja", "Garrett", "Nora", "Charles", "Madeline"]

(D)  ["Nora", "Charles", "Madeline", "Nate", "Silja", "Garrett"]

(E)  Nothing is returned. ArrayListIndexOutOfBoundsException

29 .    Consider the following code segment.

What will be printed as a result of executing the code segment?

(A)  -30 30

(B)  -4 0

(C)  0 -4

(D)  0 0

(E)  Nothing will be printed. It is an infinite loop.

30 .    Consider the following code segment.

What is the value of newGrid[2][1] as a result of executing the code segment?

(A)  3

(B)  4

(C)  5

(D)  7

(E)  Nothing is printed. There is an ArrayIndexOutOfBoundsException .

31 .    Consider the following code segment.

Which of the following shows the values in grid after executing the code segment?

(A)  

(B)  

(C)  

(D)  

(E)  

32 .    What can the following method best be described as?

(A)  Insertion sort

(B)  Selection sort

(C)  Binary search

(D)  Merge sort

(E)  Sequential search

Questions 33–36 refer to the following classes.

33 .    Which of the following will compile without error?

  1. Beverage yum1 = new Coffee();
  2. Soda yum2 = new RootBeer("large", 3.00);

III.    Beverage yum3 = new Soda("small");

(A)  I only

(B)  II only

(C)  I and II only

(D)  II and III only

(E)  I, II, and III

34 .    Which of the following must be included in the implementation of the RootBeer class?

  1. public RootBeer()
  2. public boolean hasCaffeine()

III.    public boolean isHot()

  1. public int getCalories()

(A)  I only

(B)  I and III only

(C)  II and IV only

(D)  II, III, and IV only

(E)  I, II, III, and IV

35 .    Which of the following methods could be part of the Beverage interface?

  1. boolean hasCaffeine()
  2. boolean isHot()

III.    int getCalories()

(A)  III only

(B)  I and II only

(C)  I and III only

(D)  II and III only

(E)  I, II, and III

36 .    Which of the following code segments will compile without error?

(A)  

(B)  

(C)  

(D)  

(E)  

37 .    Consider the following method.

What could replace /* missing code */ to allow the method to return the number of times letter appears in word ?

(A)  word.substring(index).equals(letter)

(B)  word.substring(index, index + 1) == letter

(C)  word.indexOf(letter) == letter.indexOf(letter)

(D)  word.substring(index, index + 1).equals(letter)

(E)  letter.equals(word.substring(index).indexOf(letter))

38 .    Assume obscureAnimals is an ArrayList<String> that has been correctly constructed and populated with the following items.

Consider the following code segment.

What will be printed as a result of executing the code segment?

(A)  []

(B)  [sugar glider]

(C)  [aye-aye, echidna, sugar glider]

(D)  [aye-aye, echidna, sugar glider, jerboa]

(E)  Nothing will be printed. There is an ArrayListIndexOutOfBoundsException .

Questions 39–40 refer to the following classes.

Consider the following class declarations.

39 .    Assume that ArrayList<Building> list has been correctly instantiated and populated with Building objects.

Which of the following code segments will result in the square feet in each building being printed?

III.    

(A)  I and IV only

(B)  I and V only

(C)  II and IV only

(D)  III and IV only

(E)  III and V only

40 .    Consider the following code segment.

What will be printed by the following code segment?

(A)  

(B)  

(C)  

(D)  

(E)  There is an error. Nothing will be printed.

STOP. End of Part I.

AP Computer Science A: Practice Exam 2

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 hex grid is a type of two-dimensional (2-D) map used by many games to represent the area that tokens, ships, robots, or other types of game pieces can move around on.

The GamePiece class is intended to represent the various game pieces required to play different games on the HexGrid . The implementation of the GamePiece class is not shown. You may construct a GamePiece object with a no-argument constructor.

A hex grid is represented in the HexGrid class by a 2-D array of GamePiece objects. The coordinates of a GamePiece represent its position on the HexGrid as shown in the following diagram. Many of the hex cells in the HexGridwill not be occupied by any GamePiece and are therefore null .

The rows in a HexGrid are in a staggered horizontal pattern where hexes in even columns rise higher than hexes in odd-numbered columns. The columns in a HexGrid always appear vertically aligned regardless of the value of the row.

The following is a representation of a HexGrid object that contains several GamePiece objects at specified locations in the HexGrid . The row and column of each GamePiece are given.

 

(a)  Write the method getGamePieceCount . The method returns the number of GamePiece objects in the hex grid.

(b)  Write the method isAbove . The method returns an ArrayList of GamePiece objects that are located "above" the GamePiece in the row and column specified in the parameters. "Above" is defined as in the same column but with a lower row number than the specified location. In the diagram below, letters represent GamePiece objects. The objects may appear in any order in the ArrayList .

  • If the method is called with the row and column of C, anArrayList containing A and B will be returned.
  • If the method is called with the row and column of F, anArrayList containing E will be returned.
  • If the method is called with the row and column of E, an emptyArrayList is returned.
  • If the method is called with the row and column of an empty cell,null is returned.

(c)  Write the addRandom method. This method takes a parameter that represents the number of GamePiece objects to be added to the grid at random locations. GamePiece objects can only be added to locations that are currently empty (null ). If there are insufficient empty cells to complete the requested additions, no GamePiece objects will be added and the method will return false . If the additions are successful, the method will return true .

You may assume that getGamePieceCount works as intended, regardless of what you wrote in part (a). You must use getGamePieceCount appropriately in order to receive full credit for part (c).

2 .    In mathematics, a monomial is a constant value multiplied by a variable raised to a power. The constant multiplier part of a monomial is called the coefficient and the value of the exponent is called the degree of the monomial.

Examples of Monomials

A monomial is represented by the following class.

In mathematics, different numbers of monomials with different degrees can be combined to create polynomial expressions.

Since all polynomials of one variable have certain characteristics in common, they are represented by a Polynomial interface. The Polynomial interface requires implementing classes to provide the getDegree , getNumTerms , and getName methods, where degree, number of terms, and name are defined as follows:

  • Thedegree is the value of the largest exponent on the variable.
  • Thenumber of terms is the number of monomials that combine to form the polynomial.
  • Thename of a polynomial is composed of two parts: the degree determines the first part, and the number of terms determines the second part as seen in the following charts and examples.

Examples

The declaration for the Polynomial interface is shown below.

 

(a)  A Quadratic is a degree 2 polynomial with one, two, or three monomial terms. The first monomial term must be of degree 2 for the object to be identified as Quadratic . The degree 1 and degree 0 terms are not required.

Examples of Quadratic Polynomials

(i)  3x 2 + 7x + 6

(ii)  2.1x 2 + 8

(iii)  4x 2

Write the complete Quadratic class that properly implements the Polynomial interface. Include a constructor that takes an ArrayList of Monomial objects as a parameter, and any necessary instance variables and methods. It is not necessary to include additional methods like toString , or accessors and modifiers for the instance variables.

Precondition: The Monomial objects in the ArrayList passed to the constructor are in order of degree. The degree 2 monomial term is at index 0, the second highest degree at index 1 (if it exists), and the third highest degree at index 2 (if it exists).

    The lists for the examples above would look like this:

(i)  

(ii)  

(iii)  

 

(b)  A quadratic can be written using a , b , and c to represent the coefficients of the various monomial terms: ax 2 + bx + c . If a term does not exist, its coefficient is zero. Given this notation, the determinant is the name used for the expression b 2 - 4ac . a , b , and c are passed to the method as parameters.

If the determinant is greater than or equal to zero, then real roots exist for this quadratic. If the determinant is negative, then there are no real roots. The hasRoots() method returns true if the determinant is greater than or equal to zero and false if the determinant is less than zero.

Write a private boolean hasRoots(double a, double b, double c) method to be included in the Quadratic class.

(c) The solutions or roots of a Quadratic polynomial are the values of x that give a result of zero when the expression is evaluated. The roots can be determined by using the two-part quadratic formula (given below). The values of a , b , and c are defined as follows:

  • ais the coefficient of the degree 2 monomial,
  • bis the coefficient of the degree 1 monomial (b = 0 if no such term exists), and
  • cis the coefficient of the degree 0 monomial (c = 0 if no such term exists).

The two equations differ only in the operator before the square root. As there are two roots, they are returned in a double array of length 2.

If the determinant is negative, there are no real number solutions. This method must check the determinant before evaluating the quadratic equation and return null if no real roots exist. (Since the determinant is under a square root symbol, it is important not to evaluate the square root if the determinant is negative.)

You may assume that hasRoots works as intended, regardless of what you wrote in part (b). You must use hasRoots appropriately in order to receive full credit for part (c).

Complete the method getRoots to be added to the Quadratic class.

3 .    A printing factory maintains many printing machines that hold rolls of paper.

The factory keeps track of its printing machines in array machines , and it keeps track of its paper supply in two lists: newRolls to hold fresh rolls and usedRolls to hold the remnants taken off the machines when they no longer hold enough paper to be usable. At the beginning of the day, usedRolls is emptied of all paper remnants and newRolls is refilled. When newRolls no longer has enough rolls available to refill all the machines, the factory must shut down for the day until its supplies are restocked. At that time, the amount of paper used for the day is calculated.

A partial PrintingFactory class is shown below.

 

(a)  Write the replacePaper method of the Machine class. This method returns the nearly empty PaperRoll and replaces it with the PaperRoll passed as a parameter.

 

(b)  Write the replacePaperRolls method of the PrintingFactory class.

At the end of each job cycle, each Machine object in machines is examined to see if its PaperRoll needs replacing. A PaperRoll is replaced when it has less than 4 meters of paper remaining. The used roll is added to the usedRolls list, while a new roll is removed from the newRolls list.

 

(c)  Write the getPaperUsed method of the PrintingFactory class.

At the end of the day, the factory calculates how much paper has been used by adding up the amount of paper used from all the rolls in the usedRolls list and all the rolls still in the machines. A brand-new paper roll has 1000 meters of paper.

Example

The tables below show the status of the factory at the end of the day.

Complete the method getPaperUsed .

4 .    In the seventeenth century, Location Numerals were invented as a new way to represent numbers. Location Numerals have a lot in common with the binary number system we use today, except that in Location Numerals, successive letters of the alphabet are used to represent the powers of two, starting with A = 20 all the way to Z = 225 .

To represent a given number as a Location Numeral (LN), the number is expressed as the sum of powers of two with each power of two replaced by its corresponding letter.

Let’s consider the decimal number 19.

  • 19 can be expressed as a sum of powers of two like this: 16 + 2 + 1.
  • So 19 would be written in binary like this: 10011.
  • We can covert 19 to LN notation by choosing the letters that correspond with 1s: EBA.
  • Since changing the order of the letters does not change their value, LN is usually written in alphabetical order: ABE.

Here are a few more examples.

A partial LocationNumeral class is shown below.

 

(a)  Write the method getLetterValue that returns the numerical value of a single LN letter.

The value of each LN letter is equal to 2 raised to the power of the letter’s position in the alphabet string. Given String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" , return the decimal value of the LN letter passed as a parameter.

 

(b)  Write the method getDecimalValue that takes a Letter Numeral and returns its decimal value.

For example, if passed the String "ACE", the method will add the decimal values of A, C, and E and return the result. In this case: 1 + 4 + 16 = 21.

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

 

(c)  Because each letter in Location Numerals doubles the value of the previous letter, you can simplify a Location Numeral by replacing any two occurrences of the same letter with the next letter of higher value. For example:

Notice that in the fourth and fifth examples, the process has to be done iteratively.

This makes adding Location Numerals very simple as shown by the following algorithm.

  • Concatenate the two Location Numerals to be added.
  • Sort the letters into alphabetical order and simplify the result.
  • BDE + AC = BDEAC = ABCDE
  • AB + ABC = ABABC = AABBC = BCC = BD

Write the method add that takes two Location Numerals and adds them together, returning the simplified sum .

LocationNumeral class contains two methods that are available for you to use: sortLocationNumeral and getLetter . Their implementations are not shown. Their documentation and method declarations are repeated below.

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

Write the method add .

STOP. End of Part II.

Practice Exam 2 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 B.

  • The outer loop will start at h = 5 and then, on successive iterations, h = 3 and h = 1.
  • The inner loop will start at k = 0, then 1 and 2.
  • The if statement will print h + k only if their sum is even (since % 2 = 0 is true only for even numbers).
  • Since h is always odd, h + k will be even only when k is also odd. That only happens once per inner loop, when k = 1. Adding h and k, we get 5 + 1 = 6, 3 + 1 = 4, and 1 + 1 = 2, so 6 4 2 is printed.

2 .  The answer is A.

  • Let’s picture our ArrayList as a table. After the first three add statements we have:
  • The set statement changes element 1:
  • Add at index 0 gives us:
  • Remove the element at index 1:
  • And finally, add “Curry” to the end of the list:

3 .  The answer is B.

  • Option I is incorrect. The outer loop begins at i = letters.length. Remember that the elements of an array start at index = 0 and end at index = length – 1. Starting the loop at i = letters.length will result in anArrayIndexOutOfBoundsException .
  • Option II is correct. The outer loop takes each letter from the string in turn, and the inner loop prints it four times, as long as it is not an "S".
  • Option III is incorrect. It correctly traverses each element in the array, but then only prints each element once, not four times.

4 .  The answer is D.

  • The constructor call creates a new Boat and the super call sets the fuel variable in the Vehicle class to 20.
  • The call to the Boat class start method:
  • begins by calling the Vehicle class start method, which prints "Vroom",
  • then calls useFuel, which calls the Vehicle class changeFuel method, which subtracts 2 from the fuel variable, and
  • finally, the start method prints "Remaining fuel" followed by the value in the Vehicle class fuel variable, which is now 18.

5 .  The answer is C.

  • The type on the left side of the assignment statement can be the same type or a super type of the object constructed on the right side of the assignment statement. The object constructed should have anis-a relationship with the declared type.
  • Option I is correct. A Boatis-a Boat.
  • Option II is correct. A Boatis-a Vehicle
  • Option III is incorrect. Although a Vehicleis-a Vehicle, it cannot be constructed because Vehicle is an abstract class.

6 .  The answer is E.

  • This is a recursive method. The first call results in:

A recursive method must approach the base case or it will infinitely recurse (until the Stack overflows). The call to weird(3) calls weird(3) again, which will call weird(3) again, which will call weird(3) again. . . .

7 .  The answer is D.

  • It is important to notice that the for loop is traversing the array from the greatest index to the least. The array is correct if every element is greater than or equal to the one before it.
  • We will return true if we traverse the entire array without finding an exception. If we find an exception, we return false, so we are looking for that exception, or values[index – 1] > values[index].
  • Option A is incorrect because of the =.
  • Note that since we must not use an index that is out of bounds, we can immediately eliminate any answer that accesses values[index + 1].

8 .  The answer is D.

  • The first nested loop initializes all the values in the array in row major order. The first value entered is 0, then 1, 2, etc. After these loops terminate, the matrix looks like this:
  • The second nested loop (for-each loops this time) traverses the array and adds all the values into the sum variable. 0 + 1 + 2 + . . . + 8 = 36.

9 .  The answer is D.

  • Option I is correct. It calls the super constructor, correctly passing on 2 parameters, and then sets its own instance variables, one to the passed parameter, one to a default value.
  • Option II is incorrect. It attempts to call the student class 2 parameter constructor, passing default values, but the year is being passed as a String, not as an int.
  • Option III is correct. There will be an implicit call to Student’s no-argument constructor.

10 .   The answer D.

  • Integer.MAX_VALUE is a large number, but repeatedly dividing by 2 will eventually result in an answer of 0 and the loop will terminate. Remember that this is integer division. Each quotient will be truncated to an integer value. There will be no decimal part.
  • In the second loop, the initial condition sets i = 0, which immediately fails the condition. The loop never executes, so nothing is printed, but the code segment terminates successfully.

11 .   The answer is A.

  • The for-each loop looks at every item in the ArrayList and adds it to sum if:
  • the value of the item > 1 (all values except 0 and 1) AND
  • the size of the list – 3 > the value of the item. Since the list has 10 elements, we can rewrite this as the value of the item < 7, which is true for all elements 6 and below.
  • Both conditions are true for 2, 3, 4, 5, 6; so the sum is 20.

12 .   The answer is C.

  • Movement in the x direction is correct for all three options.
  • Option I is incorrect. It only moves in the positive y direction.
  • Option II is incorrect. It does not deal correctly with the two ships having the same y position.
  • Option III is correct. If the two ships have the same y position, the y position is not changed.

13 .   The answer is B.

  • Option I is incorrect. The move method returns a boolean. The interface specifies a void method.
  • Option II is correct. The implementation of the move method is abstract, but that’s OK. Any class that extends Zoomer will have to provide an implementation.
  • Option III is incorrect. It uses the keywordextends in its declaration, not the keyword implements . You extend a class and implement an interface.

14 .   The answer is D.

  • Option I is correct. It might be clearer to put the && condition in parentheses, but since AND has a higher priority than OR, it will be executed first, even without the parentheses.
  • Option II is incorrect. While it seems reasonable at first glance, DeMorgan’s theorem tells us we can’t just distribute the !. We also have to change OR to AND.
  • Option III is correct. As soon as a condition evaluates to true, the method will return and no more statements will be executed. Therefore no else clauses are required. The method will return false only if none of the conditions are true.

15 .   The answer is E.

  • The loop will continue to execute until either value < 5 or calculate = false.
  • When we enter the loop, value = 33, calculate = true.
  • Since 33 % 3 = 0 we execute the first if clause and set calculate = 31.
  • 31 / 4 = 7, which is > 5, so we do not execute the second if clause.
  • The second iteration of the loop begins with value = 31 and calculate = true.
  • Since 31 % 3 != 0, we do not execute the first if clause.
  • Since 31 / 4 = 7, which is > 5, we do not execute the second if clause.
  • At this point we notice that nothing is ever going to change. Value will always be equal to 31 and calculate will always be true. This is an infinite loop.

16 .   The answer is E.

  • Remember, we only need to find one error to eliminate an option.
  • Option A is incorrect. index starts in the middle of the array and goes down to zero. We swap the item at index with the item at index + 1. We are never going to address the upper half of the array.
  • Option B is incorrect. The swap code is incomplete. We put planets[index] into s, but then never uses.
  • Option C is incorrect. It’s OK to use another array, but this code forgets to switch the order when it moves the elements into the new array. The new array is identical to the old one.
  • Option D is incorrect. At first glance, there’s no obvious error. The swap code looks correct. Although planets.length – 1 – index seems a bit complex, a few examples will show us that it does, indeed, give the element that should be swapped with the element at index: 0 7 – 0 = 7, 1  7 – 1 = 6, 2  7 – 2 = 5, 3  7 – 3 = 4, and so on. The trouble with this option is that “and so on” part. It swaps all the pairs and then continues on to swap them all again. After completing the four swaps listed above, we are done and we should stop.
  • Option E is correct. The code is the same as option D, except it stops after swapping half the elements. The other half were the partners in those first swaps, so now everything is where it should be.

17 .   The answer is A.

  • An abstract class contains method declarations for the methods that all of its subclasses have in common but may implement differently.

18 .   The answer is B.

  • The general form for generating a random number betweenhigh and low is
  • high – low + 1 = 30, low = 20, so high = 49
  • After the first statement, num is an integer between 20 and 49 (inclusive).
  • In the second statement, we add 5 to num. Now num is between 25 and 54 (inclusive).
  • In the third statement we divide by 5, remembering integer division. Now num is between 5 and 10 (inclusive).

19 .   The answer is A.

  • This loop takes pieces of the String "computer" and places them in an ArrayList of String objects.
  • The loop starts at index k = 0, and adds the word.substring(0), or the entire word, to the ArrayList. The first element of the ArrayList is "computer".
  • Then k is incremented by the k++ inside the loop, k = 1, and immediately incremented again by the instruction in the loop header, k = 2. It is bad programming style to change a loop index inside the loop, but we need to be able to read code, even if it is poorly written.
  • The second iteration of the loop is k = 2, and we add word.substring(2) or "mputer" to the ArrayList.
  • We increment k twice and add word.substring(4) or "uter".
  • We increment k twice and add word.substring(6) or "er".
  • We increment k twice and fail the loop condition. The loop terminates and the ArrayList is printed.

20 .   The answer is E.

  • We need to plug the values of x and y into the given statements to see if they always generate the correct return value.
  • Option A is incorrect. 3 > 6 is false, but should be true.
  • Option B is incorrect. 1 % 0 will fail with a division by zero error.
  • Option C is incorrect. (1 + 0) % 2 = = 0 is false, but should be true.
  • Option D is incorrect. (3 + 6) % 3 = = 6 is false, but should be true.
  • Option E works for all the given values.

21 .   The answer is B.

  • The loop will continue until numWord = words.size(), which will cause an
  • Notice that numWord is only incremented if nothing is removed from the ArrayList. That is correct because, if something is removed, the indices of the elements after that element will change. If we increment numWord each time, we will skip elements.

22 .   The answer is C.

  • This is an especially difficult example of recursion because the recursive call is not the last thing in the method. It’s also not the first thing in the method. Notice that the print happensafter the substring. So each iteration of the method will print one letter less than its parameter.
  • Let’s trace the code. 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 .

Remember that the returns are read bottom to top, so the output is "SCSPCS" in that order.

  • Note that “S”.substring(1,1) is not an error. It returns the empty string.

23 .   The answer is D.

  • Option I is correct. It uses DeMorgan’s theorem to modify the boolean condition.
  • Option II is correct. It tests the two parts of the condition separately. If either fails, it returns "Numbers are not valid".
  • Option III is incorrect. If num1 is a positive number and num2 is a negative number, but the absolute value of num2 < num1 (num1 = 5 and num2 = -2, for example), option III will return "Numbers are valid" although clearly both numbers are not >= 0.

24 .   The answer is A.

  • test1 references a TestClass object with value = 17.5 and test2 references a TestClass object with value = 9.0.
  • After the addValue and reduceValue calls, our objects look like this:
  • The assignment statement changes test2 to reference the same object as test1.
  • At this point, the object with value = 19.0 is inaccessible (unless another reference variable we don’t know about is pointing to it). The next time Java does garbage collection, it will be deleted.
  • The next reduceValue call changes our object to this:
  • The getValue statements in the next line get the same value, as test1 and test2 are pointing to the same object. 0.0 + 0.0 = 0.0.

25 .   The answer is E.

  • Let’s consider what the expression is telling us.
  • The expression is true if both truth1 and truth2 are true OR if both truth1 and truth2 are false.
  • Therefore, the expression is true as long as truth1 = = truth2.

26 .   The answer is B.

  • This method implements a standard insertion sort. In this sort, each item is taken in turn and placed in its correct position among the items to its left (with lower indices). The variable value holds the item whose turn it is to be inserted. Therefore, the values printed will simply be the values of the array, in the same order that they are processed. That’s the same order in which they appear in the initial array, except that we skip element 0 (since one element, all alone, is already sorted).

27 .   The answer is A.

  • In order for a rectangle to contain a point, the following conditions must be true:

topleftX < x < bottomRightX and topLeftY < y < bottomRightY

  • Option A is correct. These are the exact conditions used in option A, though they are in a different order.
  • Option B is incorrect because it will return true if any one of the four conditions is true.
  • Options C and D are incorrect because they attempt to make invalid calls to super or Polygon methods that do not exist.
  • Option E is incorrect. It is similar to option B, except that it will return true if two of the required conditions are true.

28 .   The answer is A.

  • Let’s show the contents of the ArrayList graphically and trace the code. The method is called with this ArrayList.
  • The first time through the loop, i = 3. The element at index 3 is removed and added to the end of the ArrayList.
  • Decrement i, i = 2, which is >= 0, so execute the loop again. The element at index 2 is removed and added to the end.
  • Decrement i, i = 1, which is >= 0, so execute the loop again. The element at index 1 is removed and added to the end.
  • Decrement i, i = 0, which is >= 0, so execute the loop again. The element at index 0 is removed and added to the end.
  • Decrement i, i = -1, which fails the loop condition. The loop terminates and the ArrayList is returned.

29 .   The answer is C.

  • Let’s trace the code.
  • The loop will execute while varA != 0 or varB > 0. Another way to say that, using DeMorgan’s theorem, is that the loop will stop executing when varA = = 0 AND varB < 0.
  • varA starts at -30 and varB starts at 30. Here’s a table of their values at the end of every iteration of the loop until the loop condition fails.

30 .   The answer is C.

  • The nested loops go through grid in row-major order, but assign into newGrid in column-major order. (Notice that newGrid is instantiated with its number of rows equal to the grid’s number of columns and its number of columns equal to the grid’s number of rows.) After executing the loops, newGrid looks like this:
  • newGrid [2][1] = 5

31 .   The answer is E.

  • The nested loops traverse the entire array. Each time through, the three assignment statements are executed. The key to the problem is the order in which these statements are executed. We need to pay attention to which values will overwrite previously assigned values.
  • On entering the loops, our array looks like this:
  • We will execute the outer loop three times, and for each of those three times, we will execute the inner loop three times.
  • The first iteration of both loops, we are changing element [0][0].
  • The first statement makes it a 1.
  • Note that this statement changes the array in row-major order.
  • The second statement makes it a 2.
  • Note that this statement changes the array in column-major order.
  • The third statement makes it a 3, so it will remain a 3.
  • Note that this statement only changes the diagonals.
  • Completing the first cycle of the inner loop, the first statement assigns a 1 to [0][1] and [0][ 2] and the second statement assigns a 2 to [1][0] and [2][0]. The third statement repeatedly sets [0][0] to 3, and since that statement is last, it will remain a 3.
  • The next cycle of the inner loop will assign a 1 to [1][0], [1][1], and[1][2]. A 2 will be assigned to [0][1], [1][1], and [2][1]. Then element [1][1] will be overwritten with a 3.
  • The third (and last) cycle of the inner loop will assign a 1 to [2][0], [2][1], and [2][2]. A 2 will be assigned to [0][2], [1][2], and [2][2]. Then element [2][2] will be overwritten with a 3.

32 .   The answer is E.

  • If this were a sorting algorithm, there would be only one parameter, the array to be sorted, and a sorted array would be returned, so we can eliminate the sorting algorithms. In addition, merge sort is recursive, and selection and insertion sorts require nested loops, neither of which appear in this code.
  • Binary search repeatedly divides the remaining section of the array in half. There’s no code that does anything like that. This is not a binary search.
  • This code goes through the array one step at a time in order. This is a sequential search algorithm.

For questions 33–36, let’s start by looking at the hierarchy described in the problem.

33 .   The answer is C.

  • Option I is correct. Beverage is an interface. It cannot be instantiated, but it can be the type of a reference variable. Since Coffeeis-a Beverage, and Coffee has a no-argument constructor, this statement is valid.
  • Option II is correct. RootBeeris-a Soda and the parameters to the constructor are correct.
  • Option III is incorrect. Soda is an abstract class and an object of type Soda cannot be instantiated.

34 .   The answer is C.

  • The RootBeer class must implement all of the abstract methods in the Soda class. There are two: hasCaffeine and getCalories.

35 .   The answer is B.

  • Since both the Soda class and the Coffee class implement Beverage, any methods that they have in common could be part of the Beverage interface, although they do not have to be.
  • Both the Soda class and the Coffee class have implementations for isHot and hasCaffeine. Those methods could be part of the Beverage interface.
  • Since the Coffee class does not have a getCalories method, getCalories cannot be part of the Beverage interface.

36 .   The answer is A.

  • We need to be sure that the ArrayList type on the right side of the assignment statement has anis-a relationship with the ArrayList type on the left side of the assignment statement (is a sub-class, or the class itself).
  • Option B is incorrect because Soda is not a sub-class of RootBeer.
  • Option C is incorrect because Beverage is not a sub-class of Soda.
  • Option E is incorrect because Coffee is not a sub-class of Soda.
  • We need to be sure that the method being called is a method appropriate to the declared type.
  • Option D is incorrect. Coffee does not have a getCalories method.

37 .   The answer is D.

  • index starts at 0 and goes to the end of the String. We want a condition that will look at the letter in word at index, compare it to the letter parameter, and count it if it is the same.
  • Option A is incorrect. The one-parameter substring includes everything from the starting index to the end of the word. We need one letter only.
  • Option B is incorrect. We cannot compare Strings with = =.
  • Option C is incorrect. indexOf will tell us whether a letter appears in a word and where it appears, but not how many times. It is possible to count the occurrences of letter using indexOf, but not this way. Option C does not change the if condition each time through the loop. It just asks the same question over and over.
  • Option D is correct. It selects one letter at index and compares it to letter using the equals method, incrementing count if they match.
  • Option E is incorrect. It will not compile. It tries to compare letter to the int returned by indexOf.

38 .   The answer is C.

  • You might expect that the loop will remove any animal whose name comes before "sugar glider" lexicographically, but removing elements from an ArrayList in the context of a loop is tricky. Let’s walk through it.
  • We start with:
  • The for loop begins, i = 0. Compare "okapi" with "pink fairy armadillo", and since "o" comes before "p", remove "okapi".
  • The next iteration begins with i = 1. The remove operation has caused all the elements’ index numbers to change. We skip "aye-aye", which is now element 0, and look at "cassowary", which we remove.
  • The next iteration begins with i = 2. Again the elements have shifted, so we skip "echidna", compare to "sugar glider" but that comes after "pink fairy armadillo" so it stays put leaving the ArrayList unchanged.
  • The next iteration begins with i = 3. Remove "jerboa".
  • i = 4, which is not < animals.size(). We exit the loop and print the ArrayList.
  • Remember that if you are going to remove elements from an ArrayList in a loop, you have to adjust the index when an element is removed so that no elements are skipped.
  • Note that if we used the loop condition i < 6 (the size of the original ArrayList), then there would have been an IndexOutOfBoundsException, but because we used animals.size(), the value changed each time we removed an element.

39 .   The answer is E.

  • Option I is incorrect. Among other errors, getNumRooms does not take a parameter.
  • Option II is incorrect. Square brackets are used to access elements of arrays, but not of ArrayLists.
  • Option III is correct.
  • Option IV is incorrect. list is the name of the ArrayList, not the name being used for each element of the ArrayList.
  • Option V is correct.

40 .   The answer is B.

  • The array holds Building objects. As long as an objectis-a Building, it can go into the array.
  • The runtime environment will look at the type of the object and call the version of getSize written specifically for that object.
  • list[0] is a Building so the Building class getSize will be used to generate the String for list[0].
  • list[1] is a House so the House class getSize will be used to generate the String for list[1].
  • list[2] references the same object as list[1]. This will generate a duplicate of the list[1] response.

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 .   Hex Grid

(a)  General Problem: Write the getGamePieceCount method that counts how many GamePiece objects are located on the grid.

Refined Problem: Traverse the 2-D array of GamePiece objects and count the number of cells that are not null.

Algorithm:

  • Create a variable to hold the count.
  • Traverse the 2-D array of values using nested loops.
  • Inside the loops, evaluate each cell of the grid to see if it is null. When we find an element that is not null, increment the count variable.
  • Once the entire array has been traversed, the value of the count variable is returned.

Java Code:

Common Errors:

  • Remember that the number of rows is grid.length and the number of columns is grid[row].length or, since all columns are the same length, grid[0].length.
  • The return statement has to be outside both loops.

Java Code Alternate Solution:

You can use for-each loops to traverse a 2-D array.

 

(b)  General Problem: Write the isAbove method that returns the GamePiece objects that are above an object at a given location on the grid.

Refined Problem: Create an ArrayList of GamePiece objects that are above the position passed in the parameter, where “above” is defined as having the same column number and a lower row number than another object. If there is no object at the location passed in, null is returned. If there are no objects above the parameter location, an empty ArrayList is returned.

Algorithm:

  • Determine whether there is a GamePiece object at the location specified. If there is not, return null.
  • Create an ArrayList to hold the GamePiece objects to be returned.
  • Look in the specified column and the rows from 0 up to the specified row. If any of those cells contain GamePiece objects, add them to the ArrayList.
  • Return the ArrayList.

Java Code:

Common Errors:

  • Do not count the object itself. That means the loop must stop at r < row, not r < row.

 

(c)  General Problem: Write the addRandom method that adds a specified number of GamePiece objects to the grid in random locations.

Refined Problem: Check to see if there are enough blank cells to add the requested objects. If there are, use a random number generator to generate a row and column number. If the cell at that location is empty, add the object, otherwise, generate a new number. Repeat until all objects have been added.

Algorithm:

  • Determine whether there are enough empty cells to hold the requested number of objects.
  • If there are not, return false.
  • Loop until all objects have been added.
  • Generate a random int between 0 and number of rows.
  • Generate a random int between 0 and number of columns.
  • Check to see if that cell is free. If it is, add object and decrease number to be added by 1.
  • Return true.

Note that this algorithm may take a very long time to run if the grid is large and mostly full. If that is the case, a more efficient algorithm is to put all available open spaces into a list and then choose a random element from that list.

Java Code:

Scoring Guidelines: Hex Grid

2 .   Quadratic

(a)  General Problem: Write the Quadratic class.

Refined Problem: Create an instance variable that is an ArrayList of Monomials. Write a one-parameter constructor that takes an ArrayList of Monomial objects and assigns it to the instance variable. The Quadratic class must implement the Polynomial interface. Implement the methods required by the interface, namely getDegree, getNumTerms, and getName.

Algorithm:

  • Write a class declaration for Quadratic that includes "implements Polynomial."
  • Declare an instance variable calledterms that is an ArrayList of Monomial.
  • Write a constructor with a parameter that is an ArrayList of Monomial and assign the parameter to the instance variableterms .
  • Write method getDegree. Since this class is the Quadratic class, the degree will always be 2.
  • Write method getNumTerms. The number of terms is the size of the ArrayList.
  • Write method getName. The name is dependent on the number of elements in the ArrayListterms and the degree which we know is 2. Our choices are: Quadratic Trinomial, Quadratic Binomial , and Quadratic Monomial.

Java Code:

Common Errors:

  • The ArrayList needs to be of type Monomial, not String or int.

Java Code Alternate Solution:

The name could be determined by using an if statement, rather than indexing into an array.

terms.size(), getDegree(), and this.getDegree() can all be used to provide the number of terms.

 

(b)  General Problem: Write a hasRoots method that returns true if the quadratic has real roots and false if it does not.

Refined Problem: Use the coefficients passed to the method as parameters to evaluate b 2 - 4ac . Return true if the answer is greater than or equal to zero and false if it is less than zero.

Algorithm:

  • EvaluateMath.pow(b, 2) - 4 * a * c
  • If the answer is >= 0 return true.
  • If the answer is < 0 return false.

Java Code:

Common Errors:

  • a, b, and c are doubles and Math.pow returns a double. Make sure that if you store the determinant in a variable, it is of type double, not int.
  • Be sure to use greater thanor equal to 0.

Java Code Alternate Solution:

  • Use a variable to hold the determinant.
  • Use multiplication rather than Math.pow.
  • Use an if statement to determine the return.

 

(c)  General Problem: Write a getRoots method for the Quadratic class that solves the quadratic equation.

Refined Problem: Find the values of all the coefficients. Call the hasRoots method to determine if real roots exist. If there are no real roots, return null. If there are real roots, solve the two versions of the quadratic formula and return the results in a two-element array of type double.

Algorithm:

  • Instantiate and initialize doubles to hold the values of a, b, and c, and a two-element array of double to hold the roots.
  • Use the methods getDegree and getCoefficient to assign values to a, b, and c.
  • The coefficient of the first term in the ArrayList will always be a.
  • If there are three terms in the ArrayList, the coefficient of the second term will be b and the coefficient of the third term will be c.
  • If there are two terms in the ArrayList, find the degree of the second term. If it is 1 assign the coefficient to b, if it is 0 assign the coefficient to c.
  • Call hasRoots to determine if this quadratic has real roots.
  • If hasRoots returns false, return null.
  • Find the two solutions, using the given equations.
  • Store the solutions in the roots array and return it.

Java Code:

Common Errors:

  • Remember that there doesn’t have to be three terms in the ArrayList. You have to check before assigning to a, b, and c.
  • If there are only two terms in the ArrayList, the first one will correspond to a, but the second could be either b or c.
  • Be really careful when writing the quadratic formula. The entire numerator needs to be in parentheses, and the entire denominator needs to be in parentheses. Close the parentheses for Math.sqrt after the c. When you think you have it right, it’s always a good idea to count the open parentheses and the close parentheses to make sure you have the same number.

Java Code Alternate Solution:

You do not have to store the coefficients in an array.

Scoring Guidelines: Quadratic

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 QuadraticDriver into your IDE along with the complete Monomial class, the Polynomial interface, and Quadratic class (including your solutions).

You will need to add this import statement as the first line in your Polynomial class: import java.util.ArrayList;

3 .   Printing Factory

(a)  General Problem: Write the replacePaper method of the Machine class.

Refined Problem: Take the new PaperRoll passed as a parameter and use it to replace the current roll. Return the used roll to the caller. Notice that this is a type of swapping and will require a temp variable.

Algorithm:

  • Create a temp variable of type PaperRoll.
  • Assign the machine’s PaperRoll paper to temp.
  • Assign the new PaperRoll passed as a parameter to the machine’s PaperRoll.
  • Return the PaperRoll in temp.

Java Code:

Common Errors:

  • It may seem like you want to do this:

But once the return statement is executed, flow of control passes back to the calling method. The second statement will never be executed.

 

(b)  General Problem: Write the replacePaperRolls method of the PrintingFactory class.

Refined Problem: Traverse the machines ArrayList checking for Machine object with PaperRoll objects that contain less than 4.0 meters of paper. Any PaperRoll objects containing less than 4.0 meters of paper need to be replaced. Get a new PaperRoll object from the newRolls ArrayList, and pass it to the Machine class replacePaper method. Place the returned used PaperRoll object on the usedRolls ArrayList.

Algorithm:

  • Write a for-each loop to traverse the machines array.
  • If the current Machine object’s PaperRoll object contains < 4.0 m of paper:
  • Take a PaperRoll object off of the newRolls ArrayList.
  • Call replacePaper passing the new roll as a parameter.
  • replacePaper will return the old PaperRoll object; put it on the usedRolls ArrayList.

Java Code:

Common Errors:

  • The syntax for accessing the amount of paper remaining is complex, especially when using a for loop instead of a for-each loop. Remember that the getMeters method is not a method of the Machine class. We have to ask each Machine object for access to its PaperRoll object and then ask the PaperRoll object how much paper it has left.

Java Code Alternate Solution #1:

Use for loops instead of for-each loops.

Use just one variable for the old and new rolls.

Java Code Alternate Solution #2:

Combine the statements and eliminate the variables altogether. This could also be done in the for loop version.

(c)  General Problem: Write the getPaperUsed method of the PrintingFactory class.

Refined Problem: The amount of paper used on each roll is 1000 minus the amount of paper remaining. First traverse the usedRolls ArrayList and add up the paper used. Next traverse the machines array and add up the paper used. These two amounts represent the total paper used. Return the sum.

Algorithm:

  • Write a for-each loop to traverse the usedRolls ArrayList.
  • Add 1000 minus paper remaining on the current roll to a running sum.
  • Write a for-each loop to traverse the machines array.
  • Add 1000 minus paper remaining on the current machine’s roll to the same running sum.
  • Return the sum.

Java Code:

Java Code Alternate Solution #1:

Use for loops instead of for-each loops.

Replace sum = sum + … with sum += …

Common Errors:

  • Remember that ArrayLists and arrays use different syntax both to access elements and to find their total number of elements.

Java Code Alternate Solution #2:

There are other ways to compute the paper use. Here we add up all the leftover paper and then subtract the total from 1000 * the total number of rolls. This technique could be combined with the for loop version, as well as the for-each loop as shown here.

Scoring Guidelines: Printing Factory

4 .   Location Numerals

(a) General Problem: Write the getLetterValue method that returns the numerical value of the given letter.

Refined Problem: Find the parameter letter’s position in the String letters. Return 2 raised to that power.

Algorithm:

  • Use indexOf to find the position of letter in the String letters.
  • Use Math.pow to raise 2 to the power of the position found.
  • Return the result.

Java Code:

 

(b)  General Problem: Write the getDecimalValue method that takes a Location Numeral and returns its decimal equivalent.

Refined Problem: Find the value of each letter in turn and add it to running total. Return the final answer.

Algorithm:

  • Create a variable to hold the running total.
  • Loop through the Location Numeral String from the letter at index 0 to the end of the String.
  • Isolate each letter, using substring.
  • Call the method getLetterValue, passing the isolated letter.
  • Add the result to the running total.
  • When the loop is complete, return the total.

Java Code:

Common Errors:

  • Don’t end the loop at numeral.length() – 1. When you notice the expressionnumeral.substring(i, i + 1) you may think that the i + 1 will cause an out of bounds exception. It would if it were the first parameter in the substring, but remember that the substring will stop before the value of the second parameter, so it will not index out of bounds. If you terminate the loop at numeral.length() – 1, you will miss the last letter in the String.
  • Be sure that you use the method you wrote in part (a). There is generally a penalty for duplication of code if you rewrite the function in another method. The problem usually has a hint when a previously written method is to be used. In this case, the problem says, “You may assume that getLetterValue works as intended, regardless of what you wrote in part (a).” That’s a sure-fire indication that you’d better use the method to solve the current problem.

 

(c)  General Problem: Write the add method to add two Location Numerals and return a simplified result.

Refined Problem: Given two Location Numerals to add together, concatenate them and then repeatedly sort and simplify until no more simplification can be done. Watch for places to use the existing methods sortLocationNumeral, getLetterValue, and getLetter.

Algorithm:

  • Concatenate the two Strings.
  • Sort the Location Numeral using the sortLocationNumeral method.
  • As long as more simplification can be done:
  • Loop through the String from beginning to end.
  • Find and remove a pair of matching letters.
  • Use getLetterValue and getLetter to find the letter next highest in value.
  • Replace the removed pair with the new letter.
  • Sort the Location Numeral using the sortLocationNumeral method.
  • Return the final result.

Java Code:

Common Errors:

  • This is a tricky piece of code. There are many places where errors can sneak in. Remember that you can earn most of the points for a question even with errors or missing sections in your code.
  • Make sure you simplify all the way. You can’t just go through the String once. As the examples show, you need to keep simplifying until the simplification process doesn’t make any changes. There are several ways to do this. The solution above uses a boolean flag that is set to true at the beginning of each iteration of the loop; it is then reset to false if any changes are made. The alternate solution compares the Strings at the beginning and end of the simplification loop to see if they are the same.
  • The multiple substrings are tricky. Use a short example and work through it by hand to be sure you haven’t made an off-by-one error.
  • Using the getLetterValue and getLetter methods is an easy way to change one letter into the next, and since the directions remind us to use them, it is the way to go. However, if you couldn’t figure out how to do it, there are other ways that it can be done, especially if you go outside of the Java subset. Remember that you may use any valid Java code; however, all questions can be solved within the Java subset, and it is recommended that you keep your code within the subset.

Java Code Alternate Solution:

The only difference between this code and the code above is the way in which it decides when the String is completely simplified.

Scoring Guidelines: Location Numerals

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 the LocationNumeralDriver into your IDE along with the LocationNumeral class (including your solutions). You will also need to:

  • Add this import statement as the first line in your LocationNumeral class:

   

  • Add the completed getLetter method to the LocationNumeral class:

   

  • Add the completed sortLocationNumeral method to the LocationNumeral class:

   

  • Here’s the LocationNumeralDriver:

   

Scoring Worksheet

This worksheet will help you to approximate your performance on Practice Exam 2 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.