Dog Walking, Signed Text, Tournament, Puzzle
Apr 3, 2026
All files
This document contains Free-Response Questions from the 2016 AP® Computer Science A exam. It covers several programming concepts and class implementations in Java.
Section 1: LogMessage and SystemLog Classes
This section focuses on processing log messages.
LogMessage Class
- Purpose: Represents a single log message with a
machineIdand adescription. - Constructor
LogMessage(String message):- Parses a log message string (format:
machineId:description). - Initializes the
machineIdanddescriptioninstance variables. - Assumes the input
messageis a valid log message with exactly one colon and no leading/trailing spaces around the colon.
- Parses a log message string (format:
- Method
containsWord(String keyword):- Determines if the
descriptionproperly contains the givenkeyword. - Conditions for proper containment:
- The
keywordmust be a substring of thedescription. - The
keywordmust be at the beginning of thedescriptionOR immediately preceded by a space. - The
keywordmust be at the end of thedescriptionOR immediately followed by a space.
- The
- Examples:
- "error on /dev/disk disk" properly contains "disk".
- "error on / dev/disk" does not properly contain "disk" (space before "disk").
- Determines if the
SystemLog Class
- Purpose: Manages a list of
LogMessageobjects. - Instance Variable:
private List<LogMessage> messageList; - Method
removeMessages(String keyword):- Removes all
LogMessageobjects frommessageListwhose descriptions properly contain the givenkeyword. - Returns: A
List<LogMessage>containing the removed entries, in their original order. - Side Effect: The
messageListis modified to contain only the entries that did not properly contain thekeyword, maintaining their original relative order. - If no messages contain the
keyword, an empty list is returned, andmessageListremains unchanged.
- Removes all
Section 2: Crossword Puzzle Grid
This section deals with creating and labeling a crossword puzzle grid.
Crossword Puzzle Grid Rules
- Definition: A 2D rectangular array of black and white squares.
- Labeling Rule: A white square is labeled with a positive number if:
- It is white, AND
- (It does not have a white square immediately above it OR it does not have a white square immediately to its left OR both).
- Labeling Order: Labeled squares are numbered consecutively starting from 1, in row-major order.
Square Class
- Purpose: Represents an individual square in the crossword grid.
- Constructor
Square(boolean isBlack, int num):- Initializes a square.
isBlack:trueif the square is black,falseotherwise.num: The number assigned to the square (positive if labeled, 0 if not).
Crossword Class
- Purpose: Represents the entire crossword puzzle grid.
- Instance Variable:
private Square[][] puzzle;(storesSquareobjects). - Constructor
Crossword(boolean[][] blackSquares):- Initializes the
puzzlegrid based on theblackSquaresinput. - Dimensions of
puzzlematchblackSquares. - Each
Squareobject is created with the correct color (isBlackbased onblackSquares[r][c]). - Squares are labeled according to the crossword labeling rule using the
toBeLabeledmethod. - Labeled squares get a positive number; unlabeled squares get 0.
- Initializes the
- Method
toBeLabeled(int r, int c, boolean[][] blackSquares):- A helper method to determine if a square at
(r, c)should be labeled. - Returns
trueif the square meets the labeling criteria (white and meets adjacency rule),falseotherwise. - Uses the
blackSquaresarray to check the color of the current square and its neighbors (above and left).
- A helper method to determine if a square at
Section 3: RandomStringChooser and RandomLetterChooser Classes
This section involves classes for randomly selecting strings.
RandomStringChooser Class
- Purpose: Selects strings from a given array randomly, making each string unavailable after selection.
- Constructor
RandomStringChooser(String[] wordArray):- Initializes the chooser with an array of strings.
- All strings are initially available.
- The original
wordArrayparameter should not be modified.
- Method
getNext():- Returns a randomly chosen string from the available strings.
- The returned string becomes unavailable for future calls.
- If no strings are available, returns the string
"NONE".
- Instance Variables: Must be private.
RandomLetterChooser Class
- Purpose: A subclass of
RandomStringChooserthat specifically handles strings composed of letters. - Constructor
RandomLetterChooser(String str):- Initializes the chooser using a given string
str. - Precondition:
strcontains only letters. - Must utilize the
getSingleLettershelper method to convert the input string into an array of single-letter strings. - Calls the superclass constructor (
RandomStringChooser) with the array of single-letter strings.
- Initializes the chooser using a given string
- Helper Method
getSingleLetters(String str):- A static method (implementation not shown in detail) that takes a string and returns an array where each element is a single-character string corresponding to a character in the input string.
- Example:
getSingleLetters("cat")returns{"c", "a", "t"}.
Section 4: StringFormatter Class
This section focuses on formatting a list of words into a string of a specified length.
Formatting Rules
- Input: A
List<String> wordList(at least two words, letters only) and a targetformattedLen. - Spaces: Spaces are inserted into the gaps between words.
- Basic Gap Width: The minimum number of spaces to be placed in each gap, calculated to distribute spaces as evenly as possible.
Basic Gap Width = (formattedLen - totalLetters) / numberOfGaps
- Leftover Spaces: Any remaining spaces after distributing the basic gap width.
Leftover Spaces = (formattedLen - totalLetters) % numberOfGaps
- Distribution: Leftover spaces are distributed one by one into the gaps from left to right.
StringFormatter Methods
totalLetters(List<String> wordList):- Calculates and returns the sum of the lengths of all strings in
wordList.
- Calculates and returns the sum of the lengths of all strings in
basicGapWidth(List<String> wordList, int formattedLen):- Calculates and returns the basic gap width using
totalLettersand the number of gaps (which iswordList.size() - 1).
- Calculates and returns the basic gap width using
leftoverSpaces(List<String> wordList, int formattedLen):- Calculates and returns the number of leftover spaces (using the modulo operator). (Implementation provided).
format(List<String> wordList, int formattedLen):- Constructs and returns the final formatted string.
- It uses
basicGapWidthandleftoverSpacesto determine the exact number of spaces between each word. - The words maintain their original order.
- Spaces are added to gaps from left to right, including the basic width plus any leftover spaces assigned to that gap.
This document contains the 2013 AP® Computer Science A Scoring Guidelines and Canonical Solutions for several questions, along with general scoring guidelines and information about The College Board. The content focuses on evaluating student code for specific programming tasks.
Question 2: TokenPass
This question assesses the ability to implement a game mechanic involving distributing tokens among players.
Part (a): TokenPass Constructor (4 points)
- Intent: To create a
TokenPassobject and correctly initialize its game state. - Key Requirements:
- Create an instance variable
boardas an integer array of sizeplayerCount. - Generate a random number between 1 and 10 (inclusive) and another random number between 0 and
playerCount - 1(inclusive). - Initialize all entries in the
boardarray with the first computed random value. - Initialize the
currentPlayerinstance variable with the second computed random value.
- Create an instance variable
Part (b): distributeCurrentPlayerTokens Method (5 points)
- Intent: To distribute tokens from the
currentPlayer's position to subsequent positions in theboardarray. - Key Requirements:
- Use the initial value of
board[currentPlayer]to determine the number of tokens to distribute. - Increment at least one board entry within a loop.
- Start the token distribution at the correct board entry (the one after
currentPlayer). - If tokens remain after reaching the end of the board, distribute the next token to position 0.
- Ensure that after distribution, the token count at each position in the
boardis correct.
- Use the initial value of
Question-Specific Penalties
- -2 (v): Consistently using an incorrect array name instead of
board. - -1 (y): Destroying persistent data (e.g., modifying
currentPlayerinappropriately). - -1 (z): Attempting to return a value from a
voidmethod.
Canonical Solution (Illustrative Code)
The provided code demonstrates a valid implementation for the constructor and the distributeCurrentPlayerTokens method, using modulo arithmetic for circular distribution.
Question 2: Download Manager (Implied by getDownloadInfo and updateDownloads)
This section details scoring for methods related to managing download information.
Part (a): getDownloadInfo Method (4 points)
- Intent: To search a download list for a requested title and return the corresponding
DownloadInfoobject if found. - Key Requirements:
- Access all necessary entries in
downloadListwithout causing bounds errors. - Correctly identify and return the matching entry if it exists.
- Call the
getTitle()method on aDownloadInfoobject from thedownloadList. - Check for equality between the title from the list object and the
titleparameter using a String equality check (e.g.,.equals()). - Return a reference to the matching object if found, or
nullif not found. An early return point is not awarded.
- Access all necessary entries in
Part (b): updateDownloads Method (5 points)
- Intent: To update the
downloadListwith information from a list of titles. - Key Requirements:
- Access all entries in the
titleslist without bounds errors. - Call
getDownloadInfo(title)to check if a title from thetitleslist exists indownloadList. - Increment the count in the matching
DownloadInfoobject if the title is found. - If the title is not found, construct a new
DownloadInfoobject with the correct information. (Note: Incrementing at the time of construction is not awarded). - Add the newly constructed object to the end of
downloadListif the title was not found. (Note: Adding more than once is not awarded).
- Access all entries in the
Question-Specific Penalties
- -1 (g): Using
getLength()/getSize()forArrayListsize. - -2 (v): Consistently using an incorrect array name instead of
downloadListortitles. - -1 (z): Attempting to return a value from a
voidmethod.
Canonical Solution (Illustrative Code)
The provided code shows how to iterate through downloadList to find a matching title and how to iterate through titles to either increment an existing download or add a new one.
Question 3: JumpingCritter (GridWorld)
This question pertains to implementing a JumpingCritter within the GridWorld simulation environment.
Part (a): getEmptyLocations Method (5 points)
- Intent: To create and return an
ArrayList<Location>containing all empty locations within the grid. - Key Requirements:
- Declare and construct an empty
ArrayList<Location>. - Access all locations in the grid without bounds errors.
- Identify empty locations within a loop.
- Create a new
Locationobject for each grid cell. - Determine if the created location is empty (i.e., contains
null). - Include all identified empty locations in the constructed
ArrayListexactly once. - Return the constructed
ArrayList(code must have examined the grid).
- Declare and construct an empty
Part (b): JumpingCritter Class (4 points)
- Intent: To define a
JumpingCritterthat extendsCritterand jumps to a randomly selected empty location. - Key Requirements:
- Declare
JumpingCritterextendingCritter. - Override the
getMoveLocations()method. - The
getMoveLocations()method should return anArrayListof empty locations obtained usingGridWorldUtilities.getEmptyLocations(getGrid()). - The
selectMoveLocationmethod (implicitly required for the critter to move) must handle thenulllocation case correctly (when no empty locations exist). - The
selectMoveLocationmethod must handle the random location selection correctly by overridinggetMoveLocations.
- Declare
Question-Specific Penalties
- -1 (s): Causing an inappropriate state change in the world (e.g., modifying the grid or other actors unintentionally).
Canonical Solution (Illustrative Code)
The provided code includes a static getEmptyLocations method and a JumpingCritter class with an overridden getMoveLocations method and a selectMoveLocation method that handles random selection and the null case.
Question 4: SkyView
This question involves processing and analyzing scan data for a sky view.
Part (a): SkyView Constructor (5 points)
- Intent: To construct a
SkyViewobject from a 1D array of scan data. - Key Requirements:
- Construct a correctly-sized 2D array of doubles (
view) and assign it to an instance variable. - Initialize at least one element of
viewwith a value from thescannedarray within a loop. - Place consecutive values from
scannedinto at least one row ofviewin their original order. - Place consecutive values from
scannedinto at least one row ofviewin reverse order. - Ensure all elements of
viewhave correct values upon exit, without bounds errors onvieworscanned.
- Construct a correctly-sized 2D array of doubles (
Part (b): getAverage Method (4 points)
- Intent: To compute and return the average of a rectangular section of the
viewarray, specified by parameters. - Key Requirements:
- Declare and initialize a double accumulator (e.g.,
sum). - Add all and only the necessary values from
viewto the accumulator, without bounds errors. - Compute the average of the specified rectangular section (sum divided by count).
- Return the computed average (the computation must involve the
viewarray).
- Declare and initialize a double accumulator (e.g.,
Question-Specific Penalties
- -2 (v): Consistently using an incorrect array name instead of
vieworscanned.
Canonical Solution (Illustrative Code)
The provided code demonstrates a constructor that populates the 2D view array, alternating between forward and reverse order for rows, and a getAverage method that iterates through a specified rectangular sub-region to calculate the average.
General Scoring Guidelines
These guidelines apply across all questions and provide a framework for awarding points and applying penalties.
Key Principles
- Rubric Precedence: The question-specific assessment rubric takes precedence over general guidelines.
- Penalty Application: Penalty points can only be deducted from points earned within a specific part of a question.
- Non-Negative Scores: No part of a question (a, b, c) can have a negative point total.
- Single Penalty Assessment: A given penalty can only be assessed once per question, even if it occurs multiple times or in different parts.
Specific Penalties
- (w) Extraneous code causing side effects (e.g., output, failure to compile).
- (x) Local variables used but not declared.
- (y) Destruction of persistent data (e.g., changing a parameter's referenced value).
- (z) Void method or constructor returning a value.
- o Extraneous code with no side effect (e.g., precondition check).
- o Spelling/case discrepancies if ambiguity exists.
- o Local variable not declared (if others are declared).
- o
privateorpublicqualifier on a local variable. - o Missing
publicqualifier on class/constructor header. - o Keyword used as an identifier.
- o Common mathematical symbols used as operators.
- o
=instead of==and vice versa. - o Array/collection access confusion (
[]vs.get). - o
length/sizeconfusion for collections/arrays. - o Extraneous
[]when referencing an entire array. - o
[i, j]instead of[i][j]. - o Extraneous size in array declaration (e.g.,
int [size] nums = new int [size];). - o Missing
;if majority are present and indentation is clear. - o Missing
{}if indentation is clear and braces are used elsewhere. - o Missing
()on parameter-less method/constructor invocations. - o Missing
()aroundiforwhileconditions.
"No Penalty" Clarification
- Spelling and case discrepancies for identifiers are considered "No Penalty" only if the correction can be unambiguously inferred from context (e.g., "ArayList" vs. "ArrayList"). If context does not allow clear inference (e.g., mistaking a class name for an object name), a penalty may apply.
The College Board Information
- The College Board is a non-profit organization focused on connecting students to college success.
- It offers programs like the SAT® and Advanced Placement (AP) Program.
- The document includes trademarks and copyright information for The College Board and its programs.
AP® Computer Science A 2014 General Scoring Guidelines
This document outlines the scoring guidelines for the AP Computer Science A exam in 2014, providing a framework for evaluating student responses to free-response questions.
Core Scoring Principles
- Rubric Precedence: The question-specific assessment rubric is the primary scoring tool and always takes precedence.
- Penalty Application: Penalty points can only be deducted from parts of a question that have already earned credit according to the rubric.
- No Negative Scores: No part of a question (a, b, c) can have a negative point total.
- Single Assessment of Penalties: A specific penalty can only be assessed once per question, even if the error occurs multiple times or in different parts of the question.
General Penalty Categories
These are common errors that may incur penalty points.
- (w) Extraneous code with side effects: Code that causes unintended consequences, such as writing to output or failing to compile.
- (x) Local variables used but not declared: Using a local variable without declaring it first.
- (y) Destruction of persistent data: Modifying the value referenced by a parameter, thus altering the original data.
- (z) Void method or constructor returning a value: Attempting to return a value from a method or constructor declared as
void.
Minor Errors (Often No Penalty)
These are less severe errors that may not result in a penalty if the intent is clear.
- Extraneous code with no side effect (e.g., precondition checks).
- Spelling/case discrepancies in identifiers if the correction is unambiguous from context.
For example, "ArayList" instead of "ArrayList" is acceptable. However, using a class name like "Bug" instead of an object name "bug" is not unambiguously inferable.
- Local variables not declared, provided other variables are declared and the code is otherwise functional.
privateorpublicqualifiers on local variables.- Missing
publicqualifier on a class or constructor header. - Keywords used as identifiers.
- Common mathematical symbols used as operators (e.g.,
xfor multiplication,.for division). - Using
=instead of==for comparison, and vice versa. - Array/collection access confusion (e.g.,
[]vs..get()). length/sizeconfusion for arrays, Strings, Lists, or ArrayLists (with or without parentheses).- Extraneous
[]when referencing an entire array. - Incorrect multi-dimensional array indexing (e.g.,
[i, j]instead of[i][j]). - Extraneous size in array declaration (e.g.,
int [size] nums = new int [size];). - Missing semicolon (
;) if the majority are present and indentation clearly conveys intent. - Missing curly braces (
{}) if indentation clearly conveys intent and they are used elsewhere. - Missing parentheses
()on parameter-less method or constructor invocations. - Parentheses
()aroundiforwhileconditions.
Question 1: Word Scramble
This question involves two parts: scrambling a single word and modifying a list of words based on the scrambling logic.
Part (a): scrambleWord Method
- Intent: To scramble a given word by swapping all letter pairs that begin with 'A'.
- Scoring Breakdown:
+1: Accesses all letters in the word from left to right without bounds errors.+1: Identifies at least one letter pair where 'A' is followed by a non-'A' character.+1: Reverses the identified pair ('A' and the next character) when constructing the result string.+1: Constructs the correct result string. A point is lost if any letters are swapped more than once. Minor loop bounds errors are acceptable.+1: Returns the constructed scrambled string.
Part (b): scrambleOrRemove Method
- Intent: To modify a list of words by replacing each word with its scrambled version (using
scrambleWord) and removing any words that remain unchanged after scrambling. - Scoring Breakdown:
+1: Accesses all words in thewordListwithout bounds errors.+1: Calls thescrambleWordmethod with a word from the list as a parameter.+1: Correctly identifies words that were unchanged by the scrambling process.+1: On exit, the list contains only the words that were changed by scrambling, maintaining their original relative order. Minor loop bounds errors are acceptable.
Canonical Solution Example (scrambleWord and scrambleOrRemove)
public static String scrambleWord (String word) {
String result = ""; // Assuming result is initialized
int current = 0;
while (current < word.length() - 1) {
if (word.substring(current, current + 1).equals("A") &&
!word.substring(current + 1, current + 2).equals("A")) {
result += word.substring(current + 1, current + 2);
result += "A";
current += 2;
} else {
result += word.substring(current, current + 1);
current++;
}
}
if (current < word.length()) {
result += word.substring(current);
}
return result;
}
public static void scrambleOrRemove (List<String> wordList) {
int index = 0;
while (index < wordList.size()) {
String word = wordList.get(index);
String scrambled = scrambleWord(word);
if (word.equals(scrambled)) {
wordList.remove(index);
} else {
wordList.set(index, scrambled);
index++;
}
}
}
Question 3: Seating Chart
This question focuses on creating and modifying a 2D array representing a seating chart.
Part (a): SeatingChart Constructor
- Intent: To initialize a
SeatingChartobject using a list of students, and specified rows and columns. - Scoring Breakdown:
+1: Correctly declares and initializes theseats2D array (Student[][] seats = new Student[rows][cols];or equivalent).+1: Accesses all elements of the inputstudentListwithout bounds errors.+1: Accesses all necessary elements of theseatsarray without bounds errors. A point is lost if access is not in column-major order (as shown in the canonical solution).+1: Assigns at least one value fromstudentListto an element in theseatsarray.+1: On exit, all elements of theseatsarray have the correct values assigned. Minor loop bounds errors are acceptable.
Part (b): removeAbsentStudents Method
- Intent: To remove students from the seating chart who have more absences than a specified limit and return the count of removed students.
- Scoring Breakdown:
+1: Accesses all elements of theseatsarray without bounds errors.+1: Calls thegetAbsenceCount()method on aStudentobject. A point is lost if thenullcase (empty seat) is not handled correctly.+1: Assignsnulltoseatsarray elements where the occupying student's absence count exceedsallowedAbsences. A point is lost if theseatsarray element is modified in other cases.+1: Computes and returns the correct number of students removed.
Question-Specific Penalties
- -2 (v): Consistently uses an incorrect array name (e.g.,
studentsinstead ofseatsorstudentList).
Canonical Solution Example (SeatingChart constructor and removeAbsentStudents)
// Constructor (Column-major order example)
public SeatingChart(List<Student> studentList, int rows, int cols) {
seats = new Student[rows][cols];
int studentIndex = 0;
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
if (studentIndex < studentList.size()) {
seats[row][col] = studentList.get(studentIndex);
studentIndex++;
}
}
}
}
// Alternative Constructor (Iterating through students)
public SeatingChart(List<Student> studentList, int rows, int cols) {
seats = new Student[rows][cols];
int row = 0;
int col = 0;
for (Student student : studentList) {
seats[row][col] = student;
row++;
if (row == rows) {
row = 0;
col++;
}
}
}
// removeAbsentStudents method
public int removeAbsentStudents(int allowedAbsences) {
int count = 0;
for (int row = 0; row < seats.length; row++) {
for (int col = 0; col < seats[0].length; col++) {
if (seats[row][col] != null && seats[row][col].getAbsenceCount() > allowedAbsences) {
seats[row][col] = null;
count++;
}
}
}
return count;
}
Question 4: Trio Class
This question involves implementing a Trio class that represents a combination of a sandwich, salad, and drink, adhering to a MenuItem interface.
- Intent: To define an implementation of the
MenuIteminterface that consists of a sandwich, salad, and drink, calculating its name and price. - Scoring Breakdown:
+1: Declares the class aspublic class Trio implements MenuItem.+1: Declares appropriate private instance variables (e.g.,Sandwich sandwich;,Salad salad;,Drink drink;).+2: Implements the constructor correctly:+1:public Trio(Sandwich sandwich, Salad salad, Drink drink)signature.+1: Initializes the instance variables using the provided parameters.
+1: Implements the interface methodsgetName()andgetPrice().+1: Constructs the correct name string (e.g., "SandwichName/SaladName/DrinkName Trio") and makes it available for return ingetName().+1: Returns the constructed name string in thegetName()method.+1: Computes the correct price. The price is the sum of the two most expensive items, or all three if they are equal.+1: Returns the computed price in thegetPrice()method.
Question-Specific Penalties
- -0: Missing or extra spaces in the name string "trio" do not incur a penalty.
- -1 (w): An extraneous default constructor that causes a side effect.
Canonical Solution Example (Trio class)
// Approach 1: Calculate name and price on demand
public class Trio implements MenuItem {
private Sandwich sandwich;
private Salad salad;
private Drink drink;
public Trio(Sandwich s, Salad sal, Drink d) {
sandwich = s;
salad = sal;
drink = d;
}
public String getName() {
return sandwich.getName() + "/" + salad.getName() + "/" + drink.getName() + " Trio";
}
public double getPrice() {
double sandwichPrice = sandwich.getPrice();
double saladPrice = salad.getPrice();
double drinkPrice = drink.getPrice();
if (sandwichPrice <= saladPrice && sandwichPrice <= drinkPrice) {
return saladPrice + drinkPrice; // Sandwich is cheapest
} else if (saladPrice <= sandwichPrice && saladPrice <= drinkPrice) {
return sandwichPrice + drinkPrice; // Salad is cheapest
} else {
return sandwichPrice + saladPrice; // Drink is cheapest
}
}
}
// Approach 2: Calculate and store name and price in constructor
public class Trio implements MenuItem {
private String name;
private double price;
public Trio(Sandwich s, Salad sal, Drink d) {
double sandwichPrice = s.getPrice();
double saladPrice = sal.getPrice();
double drinkPrice = d.getPrice();
if (sandwichPrice <= saladPrice && sandwichPrice <= drinkPrice) {
price = saladPrice + drinkPrice;
} else if (saladPrice <= sandwichPrice && saladPrice <= drinkPrice) {
price = sandwichPrice + drinkPrice;
} else {
price = sandwichPrice + saladPrice;
}
name = s.getName() + "/" + sal.getName() + "/" + d.getName() + " Trio";
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
Question 5: Director Class (Actor Extension)
This question involves extending the Rock class to create a Director class with specific behaviors related to color alternation and instructing neighbors.
- Intent: To define a
Directorclass that extendsRock. It alternates between red and green colors. If its color is green when it acts, it causes all its neighbors to turn right 90 degrees. - Scoring Breakdown:
+1: Declares the class aspublic class Director extends Rock.+2: Implements the constructor:+1:Director()constructor signature. An empty body is acceptable; point lost if extraneous code causes side effects.+1: Sets the initial color toColor.REDusingsetColor()orsuper(Color.RED).
+1: Alternates the color correctly in theact()method (red to green, green to red). A point is lost for an incorrectact()method header.+1: Instructs other actors to turn if and only if theDirector's color is green at the beginning of theact()method execution.+1: UsesgetGrid()to obtain the grid for finding neighbors.+1: Identifies all neighbors or neighboring locations correctly.+1: Accesses all identified actors or locations without bounds errors.+1: CallssetDirection()with the appropriate parameter (actor.getDirection() + Location.RIGHT) on all identified neighbors.
Canonical Solution Example (Director class)
public class Director extends Rock {
public Director() {
// Empty body is okay, initial color set by super or setColor
super(Color.RED); // Or setColor(Color.RED);
}
public void act() {
if (getColor().equals(Color.GREEN)) {
// If color is green, instruct neighbors and then turn red
ArrayList<Actor> neighbors = getGrid().getNeighbors(getLocation());
for (Actor actor : neighbors) {
actor.setDirection(actor.getDirection() + Location.RIGHT);
}
setColor(Color.RED);
} else {
// If color is red, turn green
setColor(Color.GREEN);
}
}
}
Summary of Provided Content
This document contains a collection of Java programming questions and code snippets, likely from a computer science exam or practice material. The questions cover various aspects of Java programming, including class definitions, method implementation, array manipulation, string processing, object-oriented programming concepts (inheritance, constructors), and basic control flow (loops, conditional statements).
Section 1: WordPlay Class and Execution Analysis
- Class Definition: The
WordPlayclass has aStringinstance variablewordand methods to initialize (WordPlay(String w)), update (update(String first)andupdate(String first, String second)), and retrieve (getWord()) the word. - Method Overloading: The class demonstrates method overloading with two
updatemethods having different parameter lists. - Code Execution Analysis:
- A
WordPlayobjectwpis initialized with "bandana". wp.update("d", "tie");is called. Thisupdatemethod finds the index of "d" in "bandana" (which is 2) and concatenates it with "tie", resulting inwordbecoming "2tie".wp.update("scarf");is called. Thisupdatemethod prepends "scarf" to the currentword("2tie"), resulting inwordbecoming "scarf2tie".System.out.println(wp.getWord());prints the final value ofword.
- A
- Output: The printed output is "scarf2tie".
- Note: Option (E) in the original question incorrectly states that the class doesn't compile due to two update methods; method overloading is a valid Java feature.
Section 2: BallGame Class - Simulating Throws and Calculating Averages
- Class Structure: The
BallGameclass is designed to simulate a ball-throwing game. It contains two static methods:ballThrow()andaverageThrow(). ballThrow()Method:- Purpose: Simulates a single throw and returns a score.
- Scores: Possible return values are 10, 20, 30, 40, or 50.
- Randomness: Each score has an equal probability of being returned.
- Implementation Detail: Requires generating a random number and mapping it to one of the scores.
averageThrow(int numThrows, int minScore)Method:- Purpose: Simulates
numThrowsthrows and calculates the average score of throws that exceedminScore. - Precondition:
numThrows > 0. - Logic:
- Iterates
numThrowstimes, callingballThrow()in each iteration. - Keeps track of the sum of scores greater than
minScoreand the count of such scores. - If no scores are greater than
minScore, returns 0.0. - Otherwise, returns the calculated average (sum / count).
- Iterates
- Example:
averageThrow(3, 10)would average scores from throws that are greater than 10.
- Purpose: Simulates
Section 3: SecretWord and TopSecretWord Classes - String Transformation
SecretWordClass:- Stores an
originalstring. - Has a constructor
SecretWord(String word). - Provides
getOriginal()to retrieve the original string. - Has a
transformWord()method that returns a scrambled version of the original string, leaving the original unchanged. The exact scrambling logic is not shown but implies a permutation of characters.
- Stores an
TopSecretWordClass:- Inheritance: It is a subclass of
SecretWord. - Extended Transformation: It further transforms the scrambled string returned by
SecretWord.transformWord(). - Transformation Rules:
- If the scrambled string's length is even: Replace the first half with " ".
- If the scrambled string's length is odd: Replace the second half (including the middle character if length is odd) with " *** ".
checkLength()Method: Returnstrueif the final transformed string's length is greater than 5,falseotherwise.
- Inheritance: It is a subclass of
- Sample Execution: Demonstrates how
TopSecretWordmodifies the scrambled string based on length parity.
Section 4: ArrayChecker Class - Inversions in Arrays
- Concept: An inversion in an array
numbersis a pair(numbers[j], numbers[k])wherenumbers[j] > numbers[k]andj < k. ArrayCheckerClass: Contains methods to find and analyze inversions.allInversions(int[] numbers)Method:- Purpose: Returns a list of integers representing all inversion pairs.
- Output Format: The two values of each inversion pair appear adjacently in the list (e.g.,
[larger1, smaller1, larger2, smaller2, ...]). The order of pairs in the list does not matter. - Precondition:
numbers.length >= 2and no duplicate values. - Example: For
{-3, 4, 2, 7, 1, 6}, inversions are(4, 2), (4, 1), (2, 1), (7, 1), (7, 6). The list could be[4, 2, 4, 1, 2, 1, 7, 1, 7, 6].
valueWithMostInversions(int[] numbers)Method:- Purpose: Returns the integer value from the original array that participates in the most inversion pairs.
- Precondition: At least one inversion pair exists.
- Tie-breaking: If multiple values have the maximum number of inversions, any one can be returned.
- Helper Method:
countOccur(ArrayList<Integer> nums, int value)is provided to count occurrences of a value in a list. - Logic: Likely involves calling
allInversionsfirst, then iterating through the original numbers, usingcountOccuron the inversion list to find the maximum count.
Section 5: TreasureMap Class - 2D Array Game Map
- Classes Involved:
Treasure: Represents a treasure with a random number of gold coins (getGold()).Location: Represents coordinates(row, col)on the map.TreasureMap: Represents the game map using a 2D arrayTreasure[][] map.
TreasureMap(int r, int c, ArrayList<Location> locs)Constructor:- Purpose: Initializes the
mapinstance variable. - Initialization: Creates a
Treasure[r][c]array. PlacesTreasureobjects only at theLocations specified in thelocsArrayList. All other map cells arenull. - Preconditions:
r > 0,c > 0,locsis valid and non-empty, locations are unique and within bounds.
- Purpose: Initializes the
totalGold(Location start, Location end)Method:- Purpose: Calculates the total gold coins within a rectangular sub-region of the map.
- Region: Defined by
start(top-left) andend(bottom-right)Locationobjects, inclusive. - Logic: Iterates through the rows from
start.getRow()toend.getRow()and columns fromstart.getCol()toend.getCol(). For each cell, if it's notnull, it callsgetGold()on theTreasureobject and adds it to a running total. - Preconditions:
startandendare valid locations,start.row <= end.row,start.col <= end.col.
Section 6: Miscellaneous Java Concepts and Snippets
This section contains various multiple-choice questions testing specific Java concepts:
- Q15: Array Comparison: Evaluates different implementations of
haveSameContentsto check if two arrays have the same length and elements in the same order. Implementation III is correct. - Q16: Loop Termination and Arithmetic: Analyzes a
whileloop performing subtraction and incrementing a counter. The loop terminates whenxbecomes less thany. The value ofcrepresents the number of timesywas subtracted fromx.c = x / y(integer division). Forx=102, y=5,c = 102 / 5 = 20. - Q17: Static Variables and Object State: Examines the behavior of a class with a
staticvariable (maxInitialOrder) and instance variables (numOfItems).maxInitialOrdertracks the maximum initial value passed to anyContainerconstructor.calcShippingCost()uses this static variable.c1 = new Container(10):maxInitialOrderbecomes 10.c1.numOfItems = 10.c2 = new Container(6):maxInitialOrderremains 10.c2.numOfItems = 6.c1.addItems(2):c1.numOfItemsbecomes 12.c2.addItems(4):c2.numOfItemsbecomes 10.c2.calcShippingCost(): Checks ifc2.numOfItems(10) equalsmaxInitialOrder(10). It does. ReturnsnumOfItems * 0.5=10 * 0.5 = 5.0.
- Q18: Method Calls and Side Effects: Analyzes the output of code involving calls to methods (
alpha,beta) that have both return values and print statements (System.out.print). Order of execution and side effects are crucial.alpha(w)(wherew=1): Prints2, returns3. Conditionalpha(w) > 0is true.- The
||operator short-circuits, sobeta(w)is not called. - The code inside the
ifblock executes:System.out.print(alpha(w)). alpha(w)is called again: Prints2, returns3.- Output: "22"
- Q19: String Manipulation Edge Cases: Tests the
replaceStrmethod. The method fails when the replacement stringbis the same as the character being replaceda(e.g.,replaceStr("CCD", "C", "C")). TheindexOfkeeps finding the same character, leading to an infinite loop. - Q20: Boolean Logic: Requires constructing a boolean expression that matches specific conditions:
(number > 0)OR(-10 <= number <= -5). Option (D) correctly translates this using Java syntax:(-10 <= number && number <= -5) || number > 0. - Q21: Recursion: Traces the execution of a recursive method
doSomething.doSomething(10)callsdoSomething(8) + 10doSomething(8)callsdoSomething(6) + 8doSomething(6)callsdoSomething(4) + 6doSomething(4)callsdoSomething(2) + 4doSomething(2)callsdoSomething(0) + 2doSomething(0)returns""- Result:
"" + 2 + 4 + 6 + 8 + 10= "246810"
- Q22: 2D Array Traversal: Identifies an error in a method intended to print a 2D array in row-major order. The error is that the indices
[b][a]are swapped; it should be[a][b]for row-major order. This causesArrayIndexOutOfBoundsExceptionif rows have different lengths. - Q23: Array Manipulation and Loops: Analyzes a loop that modifies an array while iterating. The loop condition
k > items.length / 2and the accessitems[k-1],items[k-2]suggest potential issues.items.length = 6.items.length / 2 = 3.- Loop starts with
k = 6. Condition6 > 3is true.sum += items[5](60).sum = 60.items[5] = items[4](50).itemsis now{10, 20, 30, 40, 50, 50}.
kbecomes 5. Condition5 > 3is true.sum += items[4](50).sum = 110.items[4] = items[3](40).itemsis now{10, 20, 30, 40, 40, 50}.
kbecomes 4. Condition4 > 3is true.sum += items[3](40).sum = 150.items[3] = items[2](30).itemsis now{10, 20, 30, 30, 40, 50}.
kbecomes 3. Condition3 > 3is false. Loop ends.- Prints
sum(150).
- Q24: Loop Condition Modification: Compares
k <= endwithk < endin aforloop withk += 2. Thek <= endcondition includesendif it matches the pattern, whilek < endexcludes it. The difference depends on whetherendis reachable by adding 2s starting fromstart. - Q25: Nested Loops and Output Count: Calculates the total number of times "Z" is printed by nested loops. The outer loop runs
ktimes, and the inner loop runsktimes for each outer iteration. Total prints =k * k. - Q26: Random Number Generation: Evaluates code segments for a method that should return "red", "blue", or "green" with equal probability (1/3 each) using
Math.random().- Segment I: Uses integer casting.
(int)(randNum * 3)produces 0, 1, or 2. Correct. - Segment II: Uses floating-point comparisons.
randNum < 1/3.0covers [0, 1/3),randNum < 2/3.0covers [1/3, 2/3). The finalelsecovers [2/3, 1). Correct. - Segment III: Has a logical error. The inner
ifconditionrandNum < 2 / 3.0is checked afterresultmight have already been set to "green" in the outerelse. IfrandNumis, say, 0.1, it setsresult = "red", then checks0.1 < 2/3.0(true), setsresult = "blue", and returnsresult. IfrandNumis 0.7, it setsresult = "green", then checks0.7 < 2/3.0(false), and returnsresult("green"). This segment seems correct despite the nested structure. - All three segments appear to work correctly.
- Segment I: Uses integer casting.
- Q27: Selection Sort Trace: Traces the
selectionSortalgorithm for three passes (outer loopj=0, 1, 2).- Initial:
[1, 6, 2, 3, 5, 1] j=0: Finds min (1 at index 5), swapselements[0]andelements[5]. Array:[1, 6, 2, 3, 5, 1]j=1: Finds min (2 at index 2), swapselements[1]andelements[2]. Array:[1, 2, 6, 3, 5, 1]j=2: Finds min (1 at index 5), swapselements[2]andelements[5]. Array:[1, 2, 1, 3, 5, 6]- After three passes (
j=2is the end point), the array is[1, 2, 1, 3, 5, 6]. This doesn't match any option exactly. Let's re-check the initial array and options. The initial array in the question text is missing, but the options suggest it might have started like[?, ?, 2, 3, 5, 1]or similar. Assuming the provided options are based on a specific initial state not fully shown, let's re-evaluate based on a common example. If the initial array was[6, 1, 2, 3, 5, 1]:j=0: Min is 1 (index 1 or 5). Let's say index 1. Swapelements[0]andelements[1]. ->[1, 6, 2, 3, 5, 1]j=1: Min is 1 (index 5). Swapelements[1]andelements[5]. ->[1, 1, 2, 3, 5, 6]j=2: Min is 2 (index 2). Swapelements[2]andelements[2]. ->[1, 1, 2, 3, 5, 6]This matches option (A).
- Initial:
- Q28: Sorting Order Modification: To sort in descending order, the comparison in selection sort needs to find the maximum element instead of the minimum. This requires changing
<to>in the comparison line (Line 3). Line 1 controls the outer loop, Line 2 the inner loop, neither directly affects the comparison logic for finding min/max. So, only Line 3 needs modification. - Q29: Inheritance and Constructors: A subclass constructor (
Beta) must initialize its superclass (Alpha) state.thingis inAlpha. To initializethingto 7, theBetaconstructor needs to call theAlphaconstructor that takes a value.super(7);is the correct way. - Q30: Integer vs. Double Arithmetic: Demonstrates integer division and modulo operations.
r = 23,t = 10.a = r % t->23 % 10 = 3.abecomes3.0(due to double assignment).b = r / t->23 / 10 = 2(integer division).bbecomes2.0(due to double assignment).- Prints
a + "+" + b-> "3.0+2.0".
- Q31: Nested Loops for Combinations: The desired output
(0,1) (0,2) (0,3) (1,2) (1,3) (2,3)suggests combinations where the inner loop variablekstarts fromj+1and goes up to3. The outer loopjgoes from 0 to 3. The inner loop needs to start afterj. Option (E)int k = j + 1; k < 4; k++achieves this. - Q32: Array Index Out of Bounds: The code attempts to compare
arr[k]witharr[k + 1]. Whenkreaches the last index (arr.length - 1),arr[k + 1]will access an index outside the array bounds, causing anArrayIndexOutOfBoundsException. - Q33: String Manipulation (Substring): Tests different ways to swap the first and last characters of a string using
substring.- Segment I:
lastChar + middlePart + firstChar. Correct. - Segment II:
str.substring(1)gets from index 1 to the end. This is the middle part plus the last character. Incorrect. - Segment III: Rebuilds the string in a complex way that seems incorrect.
- Segment I:
- Q34: Array Reversal: Implements reversing an array using a loop. The loop should iterate up to the middle of the array (
k < values.length / 2). Inside the loop,values[k]should be swapped withvalues[values.length - 1 - k]. Option (A) provides the correct condition and swap index expression. - Q35: 2D Array Iteration and Boolean Logic: Analyzes the
checkmethod.result1becomestrueif any row is special (isSpecial(d)).result2startstrueand becomesfalseif any element is not incredible (!isIncredible(n)). The outputtrue truemeansresult1is true ANDresult2is true. This requires:- At least one row is special (
result1 = true). - All elements checked are incredible (
result2remains true). Option (E) matches this: "At least one row in someArray is special, and all values in someArray are incredible."
- At least one row is special (
- Q36: Method Signature for Accessor: Asks for the correct method header to return the book title (a
String) from aBookInfoobject when called externally. It should bepublic(accessible outside) and returnString.getBookName()is the standard accessor pattern. Option (B) is correct. - Q37: 2D Array Initialization with Pattern: The board initialization requires placing 'x' based on row and column parity.
- Even rows (
row % 2 == 0): 'x' in odd columns (col % 2 != 0). - Odd rows (
row % 2 != 0): 'x' in even columns (col % 2 == 0). The code iteratescol = col + 2. This means it's placing 'x' every other column. - If
rowis even, we need 'x' in odd columns (1, 3, 5...). The inner loop should start atcol = 1. - If
rowis odd, we need 'x' in even columns (0, 2, 4...). The inner loop should start atcol = 0. The provided code snippet only has one inner loop. The logic implies the starting column depends on the row. The question asks what replaces/* expr */. If the code is intended to work for both cases with a single/* expr */, it's flawed. However, if we assume the code as written is meant to be completed, and the example shows the desired outcome: - 4x8 board.
- Row 0 (even): x at cols 1, 3, 5, 7. Inner loop starts at 1, increments by 2.
- Row 1 (odd): x at cols 0, 2, 4, 6. Inner loop starts at 0, increments by 2.
- Row 2 (even): x at cols 1, 3, 5, 7. Inner loop starts at 1, increments by 2.
- Row 3 (odd): x at cols 0, 2, 4, 6. Inner loop starts at 0, increments by 2.
The code
for (int col = /* expr */; col < board[0].length; col = col + 2)needs to handle this. The simplest interpretation is that the question implies a single starting point that works given the structure. If the goal is to place 'x' in odd columns for even rows and even columns for odd rows, and the increment is always+2, the starting point must adapt. The provided snippet doesn't show howrowparity affectscolstart. Let's re-read the prompt carefully. It asks what replaces/* expr */. The example showsxin odd columns for even rows, and even columns for odd rows. The codecol = col + 2suggests it's hitting every other column. - If
rowis even, we needcol = 1, 3, 5, 7. Start = 1. - If
rowis odd, we needcol = 0, 2, 4, 6. Start = 0. The code snippet doesn't show conditional logic for the start. Assuming the question implies a single expression that could be part of a larger conditional structure, or perhaps the example implies a specific row is being processed. Without more context or a conditional statement around the inner loop, it's hard to definitively choose. However, if we look at the pattern of placement: - Even rows: 1, 3, 5, 7...
- Odd rows: 0, 2, 4, 6...
The code
col = col + 2is fixed. The starting/* expr */must be chosen. If the code must work for all rows with a single/* expr */, it's impossible. Let's assume the question is asking for the correct starting point for the inner loop based on the row parity. The example showsxin odd columns for even rows (start=1) and even columns for odd rows (start=0). The question is poorly phrased if it expects a single expression. Let's assume it's asking for the general logic. The most common pattern would be to check row parity inside the loop or before it. If we must pick one expression for/* expr */, and consider the example: - Row 0 (even): needs cols 1, 3, 5, 7. Start = 1.
- Row 1 (odd): needs cols 0, 2, 4, 6. Start = 0.
There isn't a single value for
/* expr */that works for both. The question might be flawed or require inferring a conditional structure not shown.
- Even rows (
- Q38: Recursion and String Concatenation: Analyzes a recursive method
processWords. It concatenates words from the end of the array backwards.processWords(things, 2)callsprocessWords(things, 3) + things[2]("Gorilla")processWords(things, 3)callsprocessWords(things, 4) + things[3]("House")processWords(things, 4)callsprocessWords(things, 5) + things[4]("Car")processWords(things, 5)returns""(base caseindex >= words.length)- Result:
"" + "Car"= "Car" - Then:
"Car" + "House"= "CarHouse" - Then:
"CarHouse" + "Gorilla"= "CarHouseGorilla" - The call was
processWords(things, 2), so the final result isprocessWords(things, 3) + things[2]which is"CarHouse" + "Gorilla"= "CarHouseGorilla". - Wait, the example output is
AppleGorillaHouseCar. Let's retrace. processWords(things, 2)->processWords(things, 3) + "Gorilla"processWords(things, 3)->processWords(things, 4) + "House"processWords(things, 4)->processWords(things, 5) + "Car"processWords(things, 5)->""- Substituting back:
processWords(things, 4)returns"" + "Car"="Car"processWords(things, 3)returns"Car" + "House"="CarHouse"processWords(things, 2)returns"CarHouse" + "Gorilla"="CarHouseGorilla"
- The example output
AppleGorillaHouseCarseems to imply the call wasprocessWords(things, 1). Let's assume the code is correct and the example output is for a different call or there's a misunderstanding. If the call isprocessWords(things, 2), the output is "CarHouseGorilla". If the outputAppleGorillaHouseCaris correct, the call must have beenprocessWords(things, 1). Let's assume the code and callprocessWords(things, 2)are correct, then the output is "CarHouseGorilla". If the provided answer (E) is "AppleGorillaHouseCar", then the call must have beenprocessWords(things, 1). Let's assume the question meantprocessWords(things, 1).processWords(things, 1)->processWords(things, 2) + "Apple"processWords(things, 2)->processWords(things, 3) + "Gorilla"processWords(things, 3)->processWords(things, 4) + "House"processWords(things, 4)->processWords(things, 5) + "Car"processWords(things, 5)->""- Result:
"" + "Car"= "Car" - Result:
"Car" + "House"= "CarHouse" - Result:
"CarHouse" + "Gorilla"= "CarHouseGorilla" - Result:
"CarHouseGorilla" + "Apple"= "CarHouseGorillaApple"
- This still doesn't match. Let's re-read the code:
result = processWords (words, index + 1) + words [ index] ;. It appends the current word after the recursive call result. processWords(things, 5)->""processWords(things, 4)->processWords(things, 5) + things[4]->"" + "Car"->"Car"processWords(things, 3)->processWords(things, 4) + things[3]->"Car" + "House"->"CarHouse"processWords(things, 2)->processWords(things, 3) + things[2]->"CarHouse" + "Gorilla"->"CarHouseGorilla"processWords(things, 1)->processWords(things, 2) + things[1]->"CarHouseGorilla" + "Apple"->"CarHouseGorillaApple"processWords(things, 0)->processWords(things, 1) + things[0]->"CarHouseGorillaApple" + "Bear"->"CarHouseGorillaAppleBear"- The call is
processWords(things, 2). The output should be "CarHouseGorilla". The provided answer (E) "AppleGorillaHouseCar" is incorrect based on the code and call. There might be a typo in the question or the provided answer.
- Q39: Setter Method Signature: The code
item1.setPrice(6);attempts to call a method namedsetPrice. To change thepriceinstance variable, the method needs to accept the new value as a parameter and assign it toprice. It should bevoidbecause it modifies state, not returns a calculated value. Option (A)public void setPrice(int p)is the correct signature. - Q1 (Section I): Conditional Logic: Determines
xandyvalues to print "platypus". "platypus" is printed if theelse if (x + y < 30)condition is false AND the finalelseblock is executed.- The first
if (x > y && x % 2 == 0)must be false. - The
else if (x + y < 30)must be false, meaningx + y >= 30. - Let's test options:
- (A) x=5, y=30:
x > yis false.x+y = 35 >= 30.elseblock runs. Prints "kangaroo". - (B) x=8, y=5:
x > yis true.x % 2 == 0is true. Prints "armadillo". - (C) x=8, y=15:
x > yis false.x+y = 23 < 30. Prints "koala". - (D) x=10, y=15:
x > yis false.x+y = 25 < 30. Prints "koala". - (E) x=10, y=30:
x > yis false.x+y = 40 >= 30.elseblock runs. Prints "kangaroo".
- (A) x=5, y=30:
- None of the options result in "platypus". Re-reading the code: "platypus" is printed inside the
else ifblock, after "koala". So, the conditionx + y < 30must be TRUE. - Let's re-evaluate:
- (A) x=5, y=30:
x > yfalse.x+y=35.35 < 30false. Skipelse if.elseruns. Prints "kangaroo". - (B) x=8, y=5:
x > ytrue.x % 2 == 0true. Prints "armadillo". - (C) x=8, y=15:
x > yfalse.x+y=23.23 < 30true. Prints "koala" then "platypus". This is the correct option. - (D) x=10, y=15:
x > yfalse.x+y=25.25 < 30true. Prints "koala" then "platypus". This is also a correct option. - (E) x=10, y=30:
x > yfalse.x+y=40.40 < 30false. Skipelse if.elseruns. Prints "kangaroo".
- (A) x=5, y=30:
- Both (C) and (D) produce "koalaplatypus". Assuming only one answer is correct, there might be a nuance missed or a typo. Let's assume the question intends for only "platypus" to be printed, which isn't possible with this structure. If it means "platypus is printed", then both C and D work.
- The first
- Q2 (Section I): Method Overloading: The class
SomeMethodshas multiple methods namedtestMethodwith different parameter lists (overloading). The statementSomeMethods.testMethod(1234)calls thestaticmethodtestMethod(int value). The implementation is not shown, but the call itself is valid. The question asks what is printed. If the method prints something, it will be printed. If it returns a value that is then printed byprintln, that value will be printed. Option (E) is incorrect because the class does compile. Without the implementation, we can't know the output, but the call is valid. - Q3 (Section I): Array Indexing Loop: Analyzes
num = arr[num].arr = {4, 2, 2, 3, 1},num = 0.- k=0:
num = arr[0]->num = 4. - k=1:
num = arr[4]->num = 1. - k=2:
num = arr[1]->num = 2. - k=3:
num = arr[2]->num = 2. - k=4:
num = arr[2]->num = 2. - Loop ends.
numis 2.
- Q4 (Section I): Nested Conditionals: Determines when
zis set to 20.zis initialized to 0.if (x < y):if (x > 0):z = 10.else:z = 20. (Thiselsecorresponds tox <= 0).
else(corresponding tox >= y):zremains 0.- So,
zis 20 ifx < yANDx <= 0. Option (C) is "Whenever x is less than y and x is not greater than 0", which is equivalent tox < yandx <= 0.
- Q5 (Section I): Type Casting and Floating-Point Arithmetic:
valOne = 5.75,valTwo = 2.75.x = (int) valOne + (int) valTwo;->x = (int) 5.75 + (int) 2.75->x = 5 + 2->x = 7.y = (int) (valOne + valTwo);->y = (int) (5.75 + 2.75)->y = (int) (8.50)->y = 8.- Prints
x + "" + y-> "78".
- Q6 (Section I):
whileLoop Output:n = 0.- Loop 1:
n < 10(0<10 true).n += 2(n=2). Print "2 ". - Loop 2:
n < 10(2<10 true).n += 2(n=4). Print "4 ". - Loop 3:
n < 10(4<10 true).n += 2(n=6). Print "6 ". - Loop 4:
n < 10(6<10 true).n += 2(n=8). Print "8 ". - Loop 5:
n < 10(8<10 true).n += 2(n=10). Print "10 ". - Loop 6:
n < 10(10<10 false). Loop ends. - Output: "2 4 6 8 10 ". Option (D).
- Q7 (Section I): Conditional Logic Equivalence: Compares conditional statements. The original code is:
if (value == 7) { value++; } else { value += value; }. This means ifvalueis 7, it increments by 1. Otherwise (ifvalueis not 7), it doublesvalue. We need an equivalent structure.- Option (A):
if (value != 7) { value += value; } else { value++; }. This matches the logic exactly.
- Option (A):
- Q8 (Section I): Nested Loop Output:
- Outer loop
jfrom 0 to 3. Inner loopkfrom 0 to 2. Printsj * k. - j=0: k=0 (00=0), k=1 (01=0), k=2 (0*2=0). Prints "0 0 0 ". Newline.
- j=1: k=0 (10=0), k=1 (11=1), k=2 (1*2=2). Prints "0 1 2 ". Newline.
- j=2: k=0 (20=0), k=1 (21=2), k=2 (2*2=4). Prints "0 2 4 ". Newline.
- j=3: k=0 (30=0), k=1 (31=3), k=2 (3*2=6). Prints "0 3 6 ". Newline.
- Output:
0 0 0 0 1 2 0 2 4 0 3 6 - Option (E) matches this.
- Outer loop
- Q9 (Section I): Inheritance Syntax: Defines a subclass
Toasterthat extendsAppliance.Toasterhas an instance variablemaxSlices. The correct syntax ispublic class Toaster extends Appliance { private int maxSlices; ... }. Option (D). - Q10 (Section I): Boolean Algebra: Simplifies
(x && y) || y. Using the absorption law (A || (A && B) == A), this simplifies toy. Option (D)x || yis not equivalent. Let's recheck.- Truth Table: | x | y | x && y | (x && y) || y | x || y | |---|---|--------|----------------|--------| | T | T | T | T | T | | T | F | F | F | T | | F | T | F | T | T | | F | F | F | F | F |
- The expression
(x && y) || yis equivalent toy. Option (D)x || yis not always equivalent. Let's re-examine the expression(x && y) || y. - If
yis true, the whole expression is true. - If
yis false, the expression becomes(x && false) || false, which simplifies tofalse || false, which isfalse. - So, the expression evaluates to
y. - Which option is equivalent to
y? None of the options are simplyy. Let's re-read the question and options. - Expression:
(x && y) || y - Option (C):
x && y- Not equivalent. - Option (D):
x || y- Not equivalent (e.g., x=F, y=T -> result T, x||y is T. x=T, y=F -> result F, x||y is T). - Let's re-evaluate the truth table for
(x && y) || y:- x=T, y=T: (T && T) || T = T || T = T
- x=T, y=F: (T && F) || F = F || F = F
- x=F, y=T: (F && T) || T = F || T = T
- x=F, y=F: (F && F) || F = F || F = F
- The result is TRUE if and only if
yis TRUE. So the expression is equivalent toy. - Is there a typo in the question or options? Let's assume the question meant
x || (x && y). This simplifies tox. - Let's assume the question meant
(x || y) && y. This simplifies toy. - If the expression is indeed
(x && y) || y, it is equivalent toy. None of the options are justy. - Let's reconsider the absorption law:
A || (A && B) = A. The expression isy || (y && x). This simplifies toy. - Perhaps the question is asking which expression always evaluates to the same value as the given expression under certain conditions or if there's a simplification rule being tested.
- Let's re-check the truth table for
x || y:- x=T, y=T: T || T = T (Matches)
- x=T, y=F: T || F = T (Does NOT match, original is F)
- x=F, y=T: F || T = T (Matches)
- x=F, y=F: F || F = F (Matches)
- It seems there might be an error in the question or options provided, as
(x && y) || ysimplifies toy, and none of the options are simplyy. However, if we must choose the closest or if there's a common simplification pattern tested,x || yis often related. Let's assume there's a typo and the expression was meant to be something else, or one of the options is intended to be equivalent. Given the options, and the fact that(x && y) || yis equivalent toy, andx || yis often tested alongside these, let's stick with the analysis that it simplifies toy. If forced to choose, and assuming a potential error,x || yis a common related expression.
- Q11 (Section I): Reverse ArrayList Iteration: To print an ArrayList in reverse, the loop index
kshould start at the last index (names.size() - 1), continue as long askis non-negative (k >= 0), and decrement (k--). Option (D). - Q12 (Section I): Recursive Summation: Calculates
calc(4). This is a recursive sum:n + (n-1) + ... + 1.calc(4) = calc(3) + 4calc(3) = calc(2) + 3calc(2) = calc(1) + 2calc(1) = calc(0) + 1calc(0) = 0- Substituting back:
calc(1) = 0 + 1 = 1calc(2) = 1 + 2 = 3calc(3) = 3 + 3 = 6calc(4) = 6 + 4 = 10
- Result is 10.
- Q13 (Section I): 2D Array Row Access:
int[][] rectangle = new int[4][5];declares a 4x5 2D array.x = rectangle[0];assigns the first row (which is itself a 1D array) tox. Option (A). - Q14 (Section I): Loop Increment for Target Value: The loop
for (int v = 1; v < 20; /* missing increment */ )needstto be 13.tis not used in the loop. The loop variablevis not used either. This question seems incomplete or flawed astis never modified. Assumingtwas meant to be incremented or modified based onv. If we assumetshould be incremented byvin each step, and we wantt=13eventually. Let's assume the loop isfor (int v = 1; v < 20; v = v * C)andt += vinside.- If
C=2(Option C):vbecomes 1, 2, 4, 8, 16. Ift += v, thent = 1 + 2 + 4 + 8 + 16 = 31. - If
C=3(Option D):vbecomes 1, 3, 9. Ift += v, thent = 1 + 3 + 9 = 13. This matches. The missing increment must bev = v * 3.
- If
This summary covers the main points and analyses of the provided Java code snippets and questions.
This document contains free-response questions from the 2013 AP Computer Science A exam, focusing on Java programming. The questions cover several distinct programming scenarios.
Question 1: Music Downloads
This question deals with managing music download information.
DownloadInfo Class
- Stores a song's
titleand thenumber of times it has been downloaded. - Constructor:
DownloadInfo(String title)initializes a new download with a count of 1. getTitle(): Returns the song's title.incrementTimesDownloaded(): Increases the download count by 1.
MusicDownloads Class
- Manages a
List<DownloadInfo>calleddownloadList. - The
downloadListis guaranteed not to be null and contains no duplicate titles.
getDownloadInfo(String title) Method (Part a)
- Purpose: To find and return a reference to a
DownloadInfoobject with a matching title. - Behavior:
- Iterates through
downloadList. - If a
DownloadInfoobject's title matches the providedtitle, it returns a reference to that object. - If no match is found, it returns
null.
- Iterates through
- Precondition: The
downloadListis not null and contains no duplicate titles. - Postcondition:
downloadListremains unchanged.
updateDownloads(List<String> titles) Method (Part b)
- Purpose: To update the
downloadListbased on a list of song titles. - Behavior:
- For each
titlein the inputtitleslist:- It first tries to find an existing
DownloadInfoobject usinggetDownloadInfo(title). - If found, it calls
incrementTimesDownloaded()on that object. - If not found, it creates a new
DownloadInfoobject with thetitleand a download count of 1, and adds it to the end of thedownloadList.
- It first tries to find an existing
- For each
- Key Rules:
- Existing entries in
downloadListmaintain their order. - New entries are added to the end of the list in the order they first appear in the
titleslist. - For existing entries, the download count is increased by the number of times their title appeared in the
titleslist. - For new entries, the download count is initialized to the number of times their title appeared in the
titleslist.
- Existing entries in
Question 2: Token Pass Game
This question describes a multiplayer game involving distributing tokens on a linear board.
Game Rules
- Players are arranged on a linear board represented by an integer array (
board), where indices are player positions and values are token counts. - Each player starts with 1 to 10 tokens.
- A player is randomly chosen to start their turn.
- Turn Action:
- The current player collects all their tokens.
- Tokens are distributed one by one to players in increasing order of position, starting from the next player.
- If the highest position is reached during distribution, the next token goes to position 0 (circular distribution).
- Distribution continues until all collected tokens are distributed.
- The
currentPlayerinstance variable tracks whose turn it is.
TokenPass Class
board: Anint[]representing player positions and token counts.currentPlayer: Anintrepresenting the index of the current player.
TokenPass(int playerCount) Constructor (Part a)
- Purpose: To initialize the game board and the starting player.
- Behavior:
- Creates the
boardarray withplayerCountelements. - Fills the
boardarray with random integers between 1 and 10 (inclusive). - Initializes
currentPlayerto a random integer between 0 andplayerCount - 1(inclusive).
- Creates the
distributeCurrentPlayerTokens() Method (Part b)
- Purpose: To implement the token distribution logic for the current player's turn.
- Precondition: The
currentPlayerhas at least one token. - Postcondition: The
currentPlayerremains unchanged. - Behavior:
- Stores the number of tokens at
board[currentPlayer]into a temporary variable and setsboard[currentPlayer]to 0. - Iterates through the tokens to be distributed:
- Calculates the next player's position using a circular increment:
(currentPlayer + 1 + i) % playerCount, whereiis the token number (starting from 0). - Adds one token to the calculated player's position (
board[nextPlayer]++).
- Calculates the next player's position using a circular increment:
- Continues until all tokens from the temporary variable are distributed.
- Stores the number of tokens at
Question 3: GridWorld Critters
This question involves creating a new type of Critter for the GridWorld simulation.
GridWorldUtilities Class
- Contains static utility methods for the GridWorld.
getEmptyLocations(Grid<Actor> grid) Method (Part a)
- Purpose: To find and return a list of all empty locations in a given
grid. - Behavior:
- Iterates through all possible
Locationobjects within thegrid. - For each
Location, it checks if the grid location is empty (i.e.,grid.get(location)returnsnull). - If a location is empty, it's added to an
ArrayList<Location>.
- Iterates through all possible
- Return Value: An
ArrayList<Location>containing all empty locations. Returns an empty list if no locations are empty. - Constraint: Each empty location should appear exactly once.
JumpingCritter Class (Part b)
- Inheritance: Extends the
Critterclass. - Behavior:
act()method (implicitly inherited and not overridden): TheJumpingCritter'sact()method should utilize theGridWorldUtilities.getEmptyLocations()method.- Movement:
- It gets a list of all empty locations in its grid using
GridWorldUtilities.getEmptyLocations(grid). - If there are empty locations:
- It randomly selects one of the empty locations.
- It moves to the selected location.
- It may consume actors (like bugs) at the destination location, depending on the base
Critterclass behavior.
- If there are no empty locations:
- The
JumpingCritterremoves itself from the grid.
- The
- It gets a list of all empty locations in its grid using
- Constraint: Do NOT override the
act()method. The solution should focus on the class structure and potentially helper methods if needed, but the core logic relies on the inheritedact()method's interaction withgetEmptyLocations.
Question 4: SkyView Telescope Data
This question involves reconstructing a 2D sky view from 1D telescope scan data.
Telescope Scanning Pattern
- The telescope scans a rectangular area.
- Data is collected into a 1D array (
scanned) in "telescope order". - Telescope order involves scanning back and forth:
- Row 0: Left to Right
- Row 1: Right to Left
- Row 2: Left to Right
- ...and so on, alternating direction for each row.
SkyView Class
view: Adouble[][]representing the reconstructed 2D view of the sky.
SkyView(int numRows, int numCols, double[] scanned) Constructor (Part a)
- Purpose: To initialize the
SkyViewobject by reconstructing the 2Dviewfrom the 1Dscanneddata. - Behavior:
- Creates the
view2D array with dimensionsnumRowsxnumCols. - Copies data from the
scannedarray into theviewarray, reordering it according to the alternating scan pattern.
- Example Logic:
- The first
numColselements ofscannedfillview[0]from left to right. - The next
numColselements ofscannedfillview[1]from right to left. - The subsequent
numColselements fillview[2]from left to right, and so on.
- The first
- Creates the
- Preconditions:
numRows > 0,numCols > 0,scanned.length == numRows * numCols. - Postcondition:
viewis correctly populated and oriented.
getAverage(int startRow, int endRow, int startCol, int endCol) Method (Part b)
- Purpose: To calculate and return the average of the values within a specified rectangular sub-section of the
view. - Behavior:
- Initializes
sumto 0.0 andcountto 0. - Iterates through the rows from
startRowtoendRow(inclusive). - Within each row, iterates through the columns from
startColtoendCol(inclusive). - Adds the value
view[row][col]tosum. - Increments
count. - After iterating through all elements in the section, calculates the average as
sum / count.
- Initializes
- Preconditions: Valid row and column ranges are provided (
0 <= startRow <= endRow < view.length,0 <= startCol <= endCol < view[0].length). - Return Value: The calculated average as a
double.
2017 AP® Computer Science A Free-Response Questions Summary
This document contains free-response questions from the 2017 AP® Computer Science A exam, focusing on Java programming concepts. The questions cover the design and implementation of classes and methods, including string manipulation, integer digit processing, and 2D array analysis.
Question 1: Digits Class
This question involves processing the digits of a non-negative integer.
-
DigitsClass:- Contains an
ArrayList<Integer>nameddigitListto store the digits of a number. - The digits are stored in the same order as they appear in the original number.
- Contains an
-
Constructor
Digits(int num):- Purpose: Initializes
digitListwith the digits from the input integernum. - Precondition:
num >= 0. - Example:
new Digits(15704)results indigitListcontaining[1, 5, 7, 0, 4].new Digits(0)results indigitListcontaining[0].
- Purpose: Initializes
-
Method
isStrictlyIncreasing():- Purpose: Returns
trueif the digits indigitListare in strictly increasing order; otherwise, returnsfalse. - Definition of Strictly Increasing: Each element after the first must be greater than (but not equal to) the preceding element.
- Examples:
new Digits(7).isStrictlyIncreasing()returnstrue(single digit is considered strictly increasing).new Digits(1356).isStrictlyIncreasing()returnstrue.new Digits(1336).isStrictlyIncreasing()returnsfalse(due to repeated '3').new Digits(1536).isStrictlyIncreasing()returnsfalse('3' is not greater than '5').new Digits(65310).isStrictlyIncreasing()returnsfalse.
- Purpose: Returns
Question 2: MultPractice Class
This question involves designing a class to produce multiplication practice problems.
-
StudyPracticeInterface:- Defines two methods:
String getProblem(): Returns the current practice problem.void nextProblem(): Advances to the next practice problem.
- Defines two methods:
-
MultPracticeClass:- Implements the
StudyPracticeinterface. - Constructor
MultPractice(int firstInt, int initialSecondInt):firstInt: A constant integer used in all problems.initialSecondInt: The starting value for the second integer in the problems.
getProblem()Method:- Returns a string in the format: "
firstIntTIMESsecondInt".
- Returns a string in the format: "
nextProblem()Method:- Increments the
secondIntvalue to prepare for the next problem.
- Increments the
- Behavior: Generates a sequence of multiplication problems where the first number is constant, and the second number increments sequentially.
- Examples:
new MultPractice(7, 3):getProblem()initially returns "7 TIMES 3".- Calling
nextProblem()changes the internal state. - Subsequent
getProblem()calls would return "7 TIMES 4", "7 TIMES 5", etc.
new MultPractice(4, 12):getProblem()initially returns "4 TIMES 12".p2.nextProblem(): prepares for "4 TIMES 13".System.out.println(p2.getProblem())would print "4 TIMES 13".p2.nextProblem(); p2.nextProblem();: prepares for "4 TIMES 15".System.out.println(p2.getProblem())would print "4 TIMES 15".
- Implements the
Question 3: Phrase Class
This question involves analyzing and modifying a string stored within a class.
-
PhraseClass:- Maintains a phrase in an instance variable
currentPhrase(aString). - Constructor
Phrase(String p): InitializescurrentPhrasewith the provided stringp. toString()Method: Returns thecurrentPhrase.
- Maintains a phrase in an instance variable
-
Method
findNthOccurrence(String str, int n):- Purpose: Returns the index of the nth occurrence of substring
strwithincurrentPhrase. - Returns:
-1if the nth occurrence does not exist. - Preconditions:
str.length() > 0andn > 0. - Postcondition:
currentPhraseis not modified. - (Implementation not shown, but assumed to work correctly for other methods).
- Purpose: Returns the index of the nth occurrence of substring
-
Method
replaceNthOccurrence(String str, int n, String repl):- Purpose: Modifies
currentPhraseby replacing the nth occurrence ofstrwithrepl. - Behavior: If the nth occurrence of
strdoes not exist,currentPhraseremains unchanged. - Preconditions:
str.length() > 0andn > 0. - Requirement: Must use
findNthOccurrenceappropriately. - Examples:
phrase1 = new Phrase("A cat ate late."); phrase1.replaceNthOccurrence("at", 1, "rane");->currentPhrasebecomes"A crane ate late."phrase2 = new Phrase("A cat ate late."); phrase2.replaceNthOccurrence("at", 6, "xx");->currentPhraseremains"A cat ate late."(6th "at" doesn't exist).phrase3 = new Phrase("A cat ate late."); phrase3.replaceNthOccurrence("bat", 2, "xx");->currentPhraseremains"A cat ate late."("bat" not found).phrase4 = new Phrase("aaaa"); phrase4.replaceNthOccurrence("aa", 1, "xx");->currentPhrasebecomes"xxaa".phrase5 = new Phrase("aaaa"); phrase5.replaceNthOccurrence("aa", 2, "bbb");->currentPhrasebecomes"abbba".
- Purpose: Modifies
-
Method
findLastOccurrence(String str):- Purpose: Returns the index of the last occurrence of substring
strincurrentPhrase. - Returns:
-1ifstris not found. - Precondition:
str.length() > 0. - Postcondition:
currentPhraseis not modified. - Requirement: Must use
findNthOccurrenceappropriately. - Examples:
phrase1 = new Phrase("A cat ate late.");phrase1.findLastOccurrence("at")returns8(index of "at" in "late").phrase1.findLastOccurrence("cat ")returns4.phrase1.findLastOccurrence("bat")returns-1.
- Purpose: Returns the index of the last occurrence of substring
Question 4: Successors Class
This question involves reasoning about a 2D array of integers and their positions.
-
PositionClass:- Used to represent coordinates (row, column) within a 2D array.
- Constructor
Position(int r, int c): Creates aPositionobject. - (Instance variables, other methods not shown).
-
SuccessorsClass: (Static methods) -
Method
findPosition(int num, int[][] intArr):- Purpose: Finds the location of a given integer
numwithin a 2D integer arrayintArr. - Returns: A
Positionobject representing the (row, column) ofnum, ornullifnumis not found inintArr. - Precondition:
intArrcontains at least one row. - Example: Given
arr = {{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}:findPosition(8, arr)returnsPosition(2, 1)(assuming 0-based indexing for rows/cols in the example description, though the example output shows(2,1)for value 8 which is at row 2, col 1 in the provided array). Correction based on example: The example statesfindPosition(8, arr)returnsPosition(2, 1)for the array shown, which implies the array might be structured differently or the example has a typo. The array shown is{{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}. Value 8 is at row 0, column 3. Value 14 is at row 2, column 1. Assuming the example meantfindPosition(14, arr)returnsPosition(2, 1). Let's re-evaluate the example: "The call findPosition (8, arr) would return the Position object (2, 1) because the value 8 appears in arr at row 2 and column 1." This implies the array in the example might be different from the one depicted visually. However, if we strictly follow the visual array{{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}, then 8 is at(0, 3). If the example meant the value 14, it would be at(2, 1). We will proceed assuming the method's goal is to find the correct row/column index.findPosition(17, arr)returnsnull.
- Purpose: Finds the location of a given integer
-
Method
getSuccessorArray(int[][] intArr):- Purpose: Creates and returns a 2D successor array.
- Successor: The integer that is one greater than a given integer.
- 2D Successor Array: Has the same dimensions as
intArr. Each element at(r, c)in the successor array stores thePositionof the successor of the integer found at(r, c)inintArr. - Largest Element: The position corresponding to the largest element in
intArrisnullin the successor array, as it has no successor within the array's range. - Precondition:
intArrcontains at least one row and contains consecutive values. Each integer may be in any position. - Requirement: Must use
findPositionappropriately. - Example:
- Given
intArrcontaining numbers 5 through 16. - The successor array element corresponding to the position of
8will contain thePositionof9. - The successor array element corresponding to the position of
16(the largest) will benull.
- Given
AP® Computer Science A 2015 Free-Response Questions Summary
This document contains the free-response questions from the 2015 AP® Computer Science A exam, covering array manipulation, sparse array representation, and object-oriented design principles.
Question 1: Array Manipulation
This question focuses on processing one-dimensional and two-dimensional arrays of integers. It requires writing three static methods within a DiverseArray class.
-
arraySum(int[] arr):- Purpose: Calculates and returns the sum of all elements in a given one-dimensional integer array.
- Example: For
arr1 = {1, 2, 3, 4, 5},arraySum(arr1)returns15.
-
rowSums(int[][] arr2D):- Purpose: Calculates the sum of elements for each row in a two-dimensional integer array and returns these sums in a one-dimensional array.
- Input: A two-dimensional integer array
arr2D. - Output: A one-dimensional integer array where each element
kis the sum of rowkinarr2D. - Example: For
mat1 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}},rowSums(mat1)returns{10, 26, 42, 58}. (Note: The example in the prompt shows{16, 32, 28, 20}format1, which implies a differentmat1than the one listed in the text. The logic is to sum each row).
-
isDiverse(int[][] arr2D):- Purpose: Determines if a two-dimensional array is "diverse," meaning all its rows have unique sums.
- Input: A two-dimensional integer array
arr2D. - Output:
trueif all row sums are unique,falseotherwise. - Dependencies: Relies on
rowSums(and implicitlyarraySum). - Example:
mat1(with unique row sums) returnstrue.mat2(where the first and last rows have the same sum) returnsfalse.
Question 2: Hidden Word Game Logic
This question involves implementing the logic for a word guessing game. The HiddenWord class needs to store a hidden word and generate hints based on player guesses.
HiddenWordClass:- Constructor: Takes the
Stringrepresenting the hidden word. getHint(String guess)Method:- Purpose: Compares a
guessstring with the hidden word and returns a hint string. - Input: A
Stringguess(assumed to be the same length as the hidden word and contain only capital letters). - Output: A
Stringhint of the same length as the guess. - Hint Generation Rules:
- If
guess[i]matcheshiddenWord[i]: Hint character is'+'. - If
guess[i]is present inhiddenWordbut not at positioni: Hint character is'*'. - If
guess[i]is not present inhiddenWord: Hint character is'-'.
- If
- Important Note: Each letter in the hidden word can only be used once to match a guess letter. If a letter in the guess matches a letter in the hidden word at the correct position, that hidden word letter is "used up" and cannot be used for a
'*'match. - Example:
HiddenWord puzzle = new HiddenWord("HARPS");puzzle.getHint("AAAAA")returns"-----"puzzle.getHint("HELLO")returns"-*---"puzzle.getHint("HEART")returns"+*--*"puzzle.getHint("HARMS")returns"+*+*+"puzzle.getHint("HARPS")returns"+++++"
- Purpose: Compares a
- Constructor: Takes the
Question 3: Sparse Array Representation
This question deals with representing and manipulating sparse arrays, which are arrays where most elements are zero. It uses a SparseArrayEntry class and a SparseArray class.
-
SparseArrayEntryClass:- Purpose: Represents a single non-zero element in a sparse array.
- Instance Variables:
row,col,value. - Constructor:
SparseArrayEntry(int r, int c, int v)initializes the entry. - Methods:
getRow(),getCol(),getValue()to access the entry's properties. - Immutability: Objects are immutable after construction.
-
SparseArrayClass:- Purpose: Represents the entire sparse array using a list of
SparseArrayEntryobjects. - Instance Variables:
numRows: Total number of rows.numCols: Total number of columns.entries: AList<SparseArrayEntry>storing the non-zero elements (order is not guaranteed).
- Constructor:
SparseArray()initializes an empty sparse array. - Methods:
getNumRows(): Returns the number of rows.getNumCols(): Returns the number of columns.getValueAt(int row, int col):- Purpose: Returns the value of the element at the specified
rowandcol. - Logic: Iterates through the
entrieslist. If an entry matches the givenrowandcol, its value is returned. If no matching entry is found,0is returned. - Precondition:
0 <= row < getNumRows()and0 <= col < getNumCols().
- Purpose: Returns the value of the element at the specified
removeColumn(int col):- Purpose: Removes a specified column from the sparse array.
- Logic:
- Removes all
SparseArrayEntryobjects fromentrieswhose column index matches the specifiedcol. - Decrements the column index of all remaining
SparseArrayEntryobjects whose column index is greater thancol. - Decrements
numColsby 1.
- Removes all
- Precondition:
0 <= col < getNumCols().
- Purpose: Represents the entire sparse array using a list of
Question 4: Object-Oriented Design (Interfaces and Classes)
This question assesses understanding of interfaces, class implementation, and using interfaces in collections.
-
NumberGroupInterface:- Purpose: Defines a contract for objects that represent a group of integers.
- Method:
contains(int num): Returnstrueif the integernumis in the group,falseotherwise.
-
RangeClass:- Purpose: Implements the
NumberGroupinterface to represent a contiguous range of integers. - Instance Variables: Stores
minandmaxvalues of the range. - Constructor:
Range(int min, int max)initializes the range. Assumesmin <= max. contains(int num)Method: Returnstrueifmin <= num <= max,falseotherwise.- Example:
new Range(-3, 2)represents the group{-3, -2, -1, 0, 1, 2}.
- Purpose: Implements the
-
MultipleGroupsClass:- Purpose: Represents a collection of
NumberGroupobjects and itself acts as aNumberGroup. - Instance Variable:
groupList: AList<NumberGroup>storing the individual number groups. - Constructor: Initializes
groupList. contains(int num)Method:- Purpose: Determines if
numis contained in any of theNumberGroupobjects withingroupList. - Logic: Iterates through
groupList. If anyNumberGroup'scontains(num)method returnstrue, theMultipleGroups.contains(num)method returnstrue. If the loop finishes without findingnumin any group, it returnsfalse. - Example: If
multiple1containsnew Range(5, 8),new Range(10, 12), andnew Range(1, 6):multiple1.contains(2)returnstrue(fromnew Range(1, 6)).multiple1.contains(9)returnsfalse.multiple1.contains(6)returnstrue(from bothnew Range(5, 8)andnew Range(1, 6)).
- Purpose: Determines if
- Purpose: Represents a collection of
AP Computer Science A 2025 Free-Response Questions Summary
This document outlines the structure and content of the AP Computer Science A Free-Response Questions for the 2025 exam. Section II consists of four free-response questions and has a time limit of 1 hour and 30 minutes. All programming solutions must be written in Java. Partial credit is awarded for incomplete solutions. Students have access to Java Quick Reference information throughout the exam.
Question 1: Dog Walking Company and Dog Walker
This question focuses on simulating a dog-walking business.
1.1 DogWalkCompany Class
numAvailableDogs(int hour): Returns the number of dogs available for walking at a specifichour(0-23). The number of available dogs is always greater than 0.updateDogs(int hour, int numberDogsWalked): Decreases the number of available dogs for a givenhourby thenumberDogsWalked.- Preconditions:
0 <= hour <= 23,numberDogsWalked > 0.
- Preconditions:
1.2 DogWalker Class
- Instance Variables:
maxDogs: The maximum number of dogs a walker can handle simultaneously per hour.company: An instance ofDogWalkCompanyto which the walker is associated.
- Constructor
DogWalker(int max, DogWalkCompany comp): InitializesmaxDogsandcompany.- Precondition:
max > 0.
- Precondition:
walkDogs(int hour)(Part A):- Purpose: To walk dogs during a specific
hourand return the number of dogs walked. - Logic:
- Determines the number of dogs to walk based on
company.numAvailableDogs(hour)andmaxDogs. The walker walks the minimum of these two values. - Updates the company's available dogs using
company.updateDogs(hour, dogsWalked). - Returns the actual number of dogs walked.
- Determines the number of dogs to walk based on
- Example: If 10 dogs are available and
maxDogsis 4, the walker walks 4 dogs. If 3 dogs are available andmaxDogsis 4, the walker walks 3 dogs.
- Purpose: To walk dogs during a specific
dogWalkShift(int startHour, int endHour)(Part B):- Purpose: To calculate the total earnings for a dog-walking shift covering a range of hours.
- Logic: Iterates through each hour from
startHourtoendHour(inclusive). For each hour:- Calls
walkDogs(hour)to determine the number of dogs walked. - Calculates pay: $5 per dog walked.
- Adds a $3 bonus if:
maxDogsdogs were walked.- OR the walk occurs during peak hours (9 to 17, inclusive).
- Accumulates the earnings for the entire shift.
- Calls
- Preconditions:
0 <= startHour <= endHour <= 23.
Question 2: SignedText Class
This question involves creating a SignedText class to manage and manipulate strings with a signature.
2.1 Class Structure
- Instance Variables: Stores the first name and last name.
- Constructor
SignedText(String firstName, String lastName): Initializes the object with a first and last name.- Precondition:
lastName.length() >= 1.
- Precondition:
getSignature(): Returns a formatted signature string.- If
firstNameis empty, returnslastName. - If
firstNameis not empty, returnsfirstName.charAt(0) + "-" + lastName.
- If
addSignature(String text): Modifies a giventextstring based on the object's signature.- Logic:
- If the signature is not in
text, appends the signature to the end oftext. - If the signature is at the end of
text, returnstextunchanged. - If the signature is at the beginning of
text, removes the signature from the beginning and appends it to the end oftext.
- If the signature is not in
- Returns the potentially modified string.
- Logic:
Question 3: Tournament Competitors and Rounds
This question deals with managing competitors and building matches for a tournament.
3.1 Competitor Class
- Instance Variables:
name(String),rank(int). - Constructor
Competitor(String n, int initialRank): Initializes a competitor with a name and rank.- Precondition:
initialRank >= 1.
- Precondition:
3.2 Match Class
- Constructor
Match(Competitor one, Competitor two): Represents a match between two competitors.
3.3 Round Class
- Instance Variable:
competitorList(ArrayList<Competitor>). - Constructor
Round(String[ ] names)(Part A):- Purpose: Initializes
competitorListwithCompetitorobjects. - Logic: Creates a
Competitorobject for each name in thenamesarray. The rank of each competitor is determined by their position in thenamesarray (index 0 is rank 1, index 1 is rank 2, etc.). - Example:
{"Alex", "Ben", "Cara"}results incompetitorListcontainingCompetitor("Alex", 1),Competitor("Ben", 2),Competitor("Cara", 3).
- Purpose: Initializes
buildMatches()(Part B):- Purpose: Creates and returns an
ArrayList<Match>for the next round of the tournament. - Logic: Pairs competitors from
competitorListbased on rank.- Even number of competitors: Pairs the best with the worst, second-best with second-worst, and so on.
- Odd number of competitors: The highest-ranked competitor is ignored. The remaining competitors are paired as in the even case.
- Preconditions:
competitorListhas at least one element and is sorted by rank (best to worst). - Postcondition:
competitorListremains unchanged. - Example (Odd): If
competitorListis[{"Ben", 2}, {"Cara", 3}](after ignoring rank 1),buildMatchesreturns[Match({"Ben", 2}, {"Cara", 3})]. - Example (Even): If
competitorListis[{"Rei", 1}, {"Sam", 2}, {"Vi", 3}, {"Tim", 4}],buildMatchesreturns[Match({"Rei", 1}, {"Tim", 4}), Match({"Sam", 2}, {"Vi", 3})].
- Purpose: Creates and returns an
Question 4: SumOrSameGame Puzzle
This question involves a puzzle represented by a 2D array where elements are cleared by forming pairs.
4.1 SumOrSameGame Class
- Instance Variable:
puzzle(a 2D integer arrayint[][]). - Constructor
SumOrSameGame(int numRows, int numCols)(Part A):- Purpose: Initializes the
puzzle2D array. - Logic: Creates a
puzzlearray with dimensionsnumRowsxnumCols. Each element is filled with a random integer between 1 and 9 (inclusive), with equal probability. - Precondition:
numRows > 0,numCols > 0.
- Purpose: Initializes the
clearPair(int row, int col)(Part B):- Purpose: Attempts to find and clear a pair for the element at
(row, col). - Logic:
- Searches for another element
puzzle[r][c]such thatr >= row. - The pair is valid if
puzzle[row][col] == puzzle[r][c]ORpuzzle[row][col] + puzzle[r][c] == 10. - If a valid pair is found:
- Both
puzzle[row][col]andpuzzle[r][c]are set to 0. - Returns
true.
- Both
- If multiple pairs exist, any one can be cleared.
- If no valid pair is found, the
puzzleremains unchanged, and the method returnsfalse.
- Searches for another element
- Preconditions:
rowandcolare valid indices, andpuzzle[row][col]is between 1 and 9. - Example: If
puzzle[0][1]is 7, it can be paired withpuzzle[1][0](also 7) orpuzzle[1][5](value 3). If paired, both elements become 0. Ifpuzzle[2][0]is 1, and no other element in row 2 or later sums to 9 or is also 1,clearPairreturnsfalse.
- Purpose: Attempts to find and clear a pair for the element at
Exam Information:
- Section II consists of 4 free-response questions.
- Time limit: 1 hour and 30 minutes.
- All code must be in Java.
- Partial credit is available.
- Java Quick Reference is accessible.
- Assume methods are called with valid parameters unless otherwise specified.
- Use of provided accessible methods is expected; reimplementing them significantly will not receive full credit.
- Scratch work on paper is allowed, but only responses entered in the application will be graded.
- Students can navigate between questions in this section.
- A 5-minute warning will be indicated by the clock turning red.
苡甜甜甜,你好!以下是根据8套AP计算机科学A历年真题总览,总结出的高频知识点及核心术语(中英文对照),用表格呈现,方便你有针对性地复习。祝你考试顺利,焦虑减半哦!
| 高频知识点 | 英文原词汇/术语 | 中文解释 | 题型领域举例 | |:--------------- |:------------------------ |:------------ |:------------------------ | | 数组与ArrayList | Array, ArrayList | 数组与列表 | 遍历、查找、排序、复制、反转等 [27]Source: 2024 cs题.pdf15. Consider a method to determine whether two arrays have the same length and same values stored in the same order. public static boolean haveSameContents(int[] arr1, int[] arr2) { /* implementation not shown */ } Consider the following implementations of haveSameContents. I. return (arr1. length == arr2. length) && (arr1 == arr2) ; II. if (arr1. length != arr2. length) { return false; } for (int k = 0; k < arr1. length; k++) { return arr1 [k] == arr2 [k] ; } return true; III. if (arr1. length == arr2. length) { for (int k = 0; k < arr1. length; k++) { if (arr1[k] != arr2 [k] ) { return false; } } return true; } return false; Which of the implementations can be used so that haveSameContents will work as intended? (A) I only (B) II only (C) III only (D) I and III (E) II and III Unauthorized copying or reuse of any part of this page is illegal. -18- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App[79]Source: ap15_frq_computer_science_a.pdfComplete method isDiverse below. ** Returns true if all rows in arr2D have different row sums; * false otherwise. * / public static boolean isDiverse (int [] [] arr2D) C 2015 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -7- 2015 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS 2. Consider a guessing game in which a player tries to guess a hidden word. The hidden word contains only capital letters and has a length known to the player. A guess contains only capital letters and has the same length as the hidden word.[128]Source: ap-computer-science-a-frq-2017.pdf2017 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS (a) Write the constructor for the Digits class. The constructor initializes and fills digitList with the digits from the non-negative integer num. The elements in digitList must be Integer objects representing single digits, and appear in the same order as the digits in num. Each of the following examples shows the declaration of a Digits object and the contents of digitList as initialized by the constructor. Example 1 Digits d1 = new Digits (15704) ; d1: digitList: 1 0 1 2 3 Example 2 Digits d2 = new Digits (0) ; d2 : digitList: 0 | | 字符串处理 | String, substring, indexOf, equals | 字符串操作 | 查找子串、替换、拼接、字符判断 [72]Source: ap-computer-science-a-frq-2017.pdfWRITE YOUR SOLUTION ON THE NEXT PAGE. @ 2017 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -4- 2017 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS The Phrase class includes the method findNthOccurrence, which returns the nth occurrence of a given string. You must use findNthOccurrence appropriately to receive full credit. Complete method replaceNthOccurrence below. / ** Modifies the current phrase by replacing the nth occurrence of str with repl. * If the nth occurrence does not exist, the current phrase is unchanged. * Precondition: str. length () > 0 and n > 0[130]Source: ap-computer-science-a-frq-2017.pdfxxaa Phrase phrase5 = new Phrase ( "aaaa" ) ; phrase5. replaceNthOccurrence ( "aa", 2, "bbb") ; System. out . println (phrase5) ; abbba Class information for this question public class Phrase private String current Phrase public Phrase (String p) public int findNthOccurrence (String str, int n) public void replaceNthOccurrence (String str, int n, String repl) public int findLastOccurrence (String str) public String toString ()[22]Source: 2024 cs题.pdf19. Consider the method replaceStr, which is intended to return a string that is identical to orig except that all occurrences of string a are replaced by string b. / ** Precondition: a. length() == 1; b. length() == 1 */ public static String replaceStr(String orig, String a, String b) { int position = orig. indexOf (a) ; while (position != - 1) { orig = orig. substring(0, position) + b + orig. substring (position + 1) ; position = orig. indexOf (a) ; } return orig; } Which of the following statements can be used to show that replaceStr does not always work as intended? (A) String str = replaceStr("", "C", "D") ; // str should be set to "" (B) String str = replaceStr("AB", "C", "D") ; // str should be set to "AB" (C) String str = replaceStr("C", "C", "D") ; // str should be set to "D" (D) String str = replaceStr("CCC", "C", "D"); // str should be set to "DDD" (E) String str = replaceStr("CCD", "C", "C") ; // str should be set to "CCD" Unauthorized copying or reuse of any part of this page is illegal. -23- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 20. Which of the following Java expressions evaluates to true if the int variable number is positive or is between -10 and -5, inclusive, and evaluates to false otherwise? (A) (-10 <= number <= - 5) | | number > 0 (B) (-10 <= number 11 number <= - 5) | | number > 0 (C) (-10 <= number 11 number <= - 5) && number > 0 (D) (-10 <= number && number <= - 5) | | number > 0 (E) (-10 <= number && number <= - 5) && number > 0 Unauthorized copying or reuse of any part of this page is illegal. -24- GO ON TO THE NEXT PAGE. | | 类与对象 | Class, Object, Constructor, Instance Variable | 面向对象基本概念 | 构造方法、对象属性、封装、实例化 [9]Source: 2024 cs题.pdf-7- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 2. The SecretWord class is used to store and transform a string. public class SecretWord { / ** The secret word * / private String original; / ** Constructs a SecretWord object with the string word * Precondition: word is not an empty String. * / public SecretWord (String word) { /* implementation not shown */ } / ** Returns original */ public String getOriginal () { /* implementation not shown */ } / ** Returns a scrambled version of original, which has the same length as original * Postcondition: original is unchanged. */ public String transformWord () { /* implementation not shown */ } } You will write a class TopSecretWord, which is a subclass of SecretWord. The TopSecretWord class further transforms the scrambled version of the original string based on the following rules, in a way that may change the length of the string. The TopSecretWord class contains an additional method, checkLength, which returns true if the length of the result of the TopSecretWord transformation is greater than 5 and returns false otherwise. Unauthorized copying or reuse of any part of this page is illegal. -8- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App The following table contains a sample code execution sequence and the corresponding results. The code execution sequence appears in a class other than SecretWord or TopSecretWord. Statement[129]Source: ap-computer-science-a-frq-2017.pdf(2,1) Class information for this question public class Position public Position (int r, int c) public class Successors public static Position findPosition (int num, int [] [] intArr) public static Position [] [] getSuccessorArray ( int [] [] intArr) @ 2017 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -18- 2017 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS | | 继承与多态 | Inheritance, extends, implements, Polymorphism, Interface | 继承、多态、接口 | 子类构造、方法重写、接口实现 [14]Source: ap14_comp_sci_scoring_guidelines.pdfAP AP® Computer Science A 2014 Scoring Guidelines @ 2014 The College Board. College Board, Advanced Placement Program, AP, AP Central, and the acorn logo are registered trademarks of the College Board. Visit the College Board on the Web: www. collegeboard. org. AP Central is the official online home for the AP Program: apcentral. collegeboard. org. CollegeBoard AP® COMPUTER SCIENCE A 2014 GENERAL SCORING GUIDELINES Apply the question assessment rubric first, which always takes precedence. Penalty points can only be deducted in a part of the question that has earned credit via the question rubric. No part of a question (a, b, c) may have a negative point total. A given penalty can be assessed only once for a question, even if it occurs multiple times or in multiple parts of that question. 1-Point Penalty (w) Extraneous code that causes side effect (e. g. , writing to output, failure to compile)[21]Source: ap15_frq_computer_science_a.pdf-15- 2015 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS 4. This question involves the design of an interface, writing a class that implements the interface, and writing a method that uses the interface. (a) A number group represents a group of integers defined in some way. It could be empty, or it could contain one or more integers. Write an interface named NumberGroup that represents a group of integers. The interface should have a single contains method that determines if a given integer is in the group. For example, if group1 is of type NumberGroup, and it contains only the two numbers -5 and 3, then group1. contains (-5) would return true, and group1. contains (2) would return false. Write the complete NumberGroup interface. It must have exactly one method. Part (b) begins on page 17. C 2015 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -16-[40]Source: 2024 cs题.pdf(C) public class Toaster { private int maxSlices; / / There may be instance variables, constructors, and methods not shown. } (D) public class Toaster extends Appliance { private int maxSlices; / / There may be instance variables, constructors, and methods not shown. } (E) public class Toaster extends Appliance { private Toaster maxSlices; / / There may be instance variables, constructors, and methods not shown. } Unauthorized copying or reuse of any part of this page is illegal. -13- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 10. Assume that x and y are boolean variables and have been properly initialized. (x && y) | | y Which of the following always evaluates to the same value as the preceding expression? (A) x (B) y (C) x && Y (D) x | | y (E) x != y 11. Consider the following method, which is intended to print the ArrayList names in reverse order. public static void printInReverseOrder (ArrayList<String> names) { for ( /* missing control expressions */ ) { System. out. println(names. get(k)); } } Which of the following can be used to replace /* missing control expressions * / so that printInReverseOrder will work as intended? (A) int k = 0; k < names. size() ; k++ (B) int k = 0; k < names. size() - 1; k++ | | 封装及访问控制 | private, public, getter/setter | 封装、访问修饰 | 成员变量私有,getter/setter方法 [131]Source: ap14_comp_sci_scoring_guidelines.pdf+1 Calls scrambleWord with a word from the list as parameter +1 Identifies words unchanged by scrambling +1 On exit: List includes all and only words that have been changed by scrambling once, in their original relative order (minor loop bounds errors ok) c 2014 The College Board. Visit the College Board on the Web: www. collegeboard. org. AP® COMPUTER SCIENCE A 2014 CANONICAL SOLUTIONS Question 1: Word Scramble Part (a): public static String scrambleWord (String word) { int current = 0; String result=""; while (current < word. length () -1) {[150]Source: ap14_comp_sci_scoring_guidelines.pdf-0 Missing or extra spaces in name string, "trio" -1 (w) Extraneous default constructor that causes side effect c 2014 The College Board. Visit the College Board on the Web: www. collegeboard. org. AP® COMPUTER SCIENCE A 2014 CANONICAL SOLUTIONS Question 4: Trio public class Trio implements MenuItem { private Sandwich sandwich; private Salad salad; private Drink drink; public Trio (Sandwich s, Salad sal, Drink d) { sandwich = s; salad = sal; drink = d; } public String getName () { return sandwich. getName () + "/" + salad. getName () + "/" + drink. getName () + " Trio"; } public double getPrice () { double sandwichPrice = sandwich. getPrice () ; double saladPrice = salad. getPrice () ; double drinkPrice = drink. getPrice () ; if (sandwichPrice <= saladPrice && sandwichPrice <= drinkPrice) return saladPrice + drinkPrice; else if (saladPrice <= sandwichPrice && saladPrice <= drinkPrice) return sandwichPrice + drinkPrice; else return sandwichPrice + saladPrice; } | | 控制结构 | if-else, for, while, do-while, switch | 条件与循环结构 | 条件分支、循环遍历、嵌套循环 [16]Source: 2024 cs题.pdf(C) int k = names. size() ; k >= 0; k -- (D) int k = names. size() - 1; k >= 0; k -- (E) int k = names. size() - 1; k > 0; k -- Unauthorized copying or reuse of any part of this page is illegal. 0. 00 -14- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 12. Consider the following method. public static int calc(int n) { if (n == 0) { return 0; } else { return calc (n - 1) + n; } What value is returned as a result of the call calc (4) ? } (A) 0 (B) 1 (C) 3 (D) 6 (E) 10 Unauthorized copying or reuse of any part of this page is illegal. -15- GO ON TO THE NEXT PAGE.[33]Source: 2024 cs题.pdffor (int j = 0; j <= 3; j++) { for (int k = 0; k < 3; k++) { System. out. print(j * k + " "); } System. out. println(); } What is printed as a result of executing the code segment? (A) 0 0 0 01 2 0 24 (B) 0 0 0 01 2 0 2 4 0 36 (C) 0 0 0 0 01 2 3 0 24 6 0369 (D) 1 2 3 2 4 6 3 6 9 (E) 0 1 2 3 024 6 0369 Unauthorized copying or reuse of any part of this page is Illegal. -12- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 9. The Toaster class is a subclass of the Appliance class. The Toaster class has an instance variable maxSlices, which is the maximum number of slices of toast that the toaster can make at the same time. Which of the following is a correct partial definition of the Toaster class? (A) public class Appliance { private Toaster maxSlices; / / There may be instance variables, constructors, and methods not shown. } (B) public class Appliance extends Toaster { private int maxSlices; / / There may be instance variables, constructors, and methods not shown. }[60]Source: ap16_frq_computer_science_a.pdfC 2016 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -2- 2016 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS Write the entire RandomStringChooser class. Your implementation must include an appropriate constructor and any necessary methods. Any instance variables must be private. The code segment in the example above should have the indicated behavior (that is, it must compile and produce a result like the possible output shown). Neither the constructor nor any of the methods should alter the parameter passed to the constructor, but your implementation may copy the contents of the array. Part (b) begins on page 4. @ 2016 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -3- 2016 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS | | 静态成员 | static, static method/variable | 静态方法/静态变量 | 比较static与实例成员 [53]Source: 2024 cs题.pdfCS 扫描全能王 3亿人都在用的扫描App 29. Consider the following class declarations. public class Alpha { private int thing; public Alpha () { thing = 0; } public Alpha (int val) { thing = val; } } public class Beta extends Alpha { public Beta () { /* missing implementation * / } } Which of the following can be used to replace /* missing implementation * / so that the constructor for Beta initializes the value of thing to 7 ? (A) thing = 7; (B) Alpha. thing = 7; (C) super (7) ; (D) super. thing = 7; (E) super. Alpha (7); Unauthorized copying or reuse of any part of this page is Illegal. -34- 1 GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 30. Consider the following code segment. | | 集合类 | List, Set, Map, ArrayList | 集合类操作 | 元素添加、删除、遍历、查找 [5]Source: ap-computer-science-a-frq-2017.pdfC 2017 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -9- 2017 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS Interface information for this question public interface StudyPractice String getProblem () void nextProblem () Write the complete MultPractice class. Your implementation must be consistent with the specifications and the given examples. C 2017 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -10-[48]Source: ap15_frq_computer_science_a.pdf2015 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS (c) The MultipleGroups class (not shown) represents a collection of NumberGroup objects and is a NumberGroup. The MultipleGroups class stores the number groups in the instance variable groupList (shown below), which is initialized in the constructor. private List<NumberGroup> groupList; Write the MultipleGroups method contains. The method takes an integer and returns true if and only if the integer is contained in one or more of the number groups in groupList. For example, suppose multiple1 has been declared as an instance of MultipleGroups and consists of the three ranges created by the calls new Range (5, 8), new Range (10, 12), and new Range (1, 6). The following table shows the results of several calls to contains. Call Result multiple1. contains (2) true multiple1. contains (9) | | 方法签名与重载 | Method signature, Overloading | 方法重载 | 同名不同参的方法 [2]Source: ap-computer-science-a-frq-2017.pdf-8- AP CollegeBoard AP Computer Science A Free-Response Questions @ 2017 The College Board. College Board, Advanced Placement Program, AP, AP Central, and the acorn logo are registered trademarks of the College Board. Visit the College Board on the Web: www. collegeboard. org. AP Central is the official online home for the AP Program: apcentral. collegeboard. org. 2017 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS COMPUTER SCIENCE A SECTION II Time-1 hour and 30 minutes Number of questions-4 Percent of total score-50 Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Notes: · In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit.[131]Source: ap14_comp_sci_scoring_guidelines.pdf+1 Calls scrambleWord with a word from the list as parameter +1 Identifies words unchanged by scrambling +1 On exit: List includes all and only words that have been changed by scrambling once, in their original relative order (minor loop bounds errors ok) c 2014 The College Board. Visit the College Board on the Web: www. collegeboard. org. AP® COMPUTER SCIENCE A 2014 CANONICAL SOLUTIONS Question 1: Word Scramble Part (a): public static String scrambleWord (String word) { int current = 0; String result=""; while (current < word. length () -1) { | | 接口与抽象类 | Interface, implements, abstract | 接口、抽象类 | 接口声明与实现,抽象方法 [21]Source: ap15_frq_computer_science_a.pdf-15- 2015 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS 4. This question involves the design of an interface, writing a class that implements the interface, and writing a method that uses the interface. (a) A number group represents a group of integers defined in some way. It could be empty, or it could contain one or more integers. Write an interface named NumberGroup that represents a group of integers. The interface should have a single contains method that determines if a given integer is in the group. For example, if group1 is of type NumberGroup, and it contains only the two numbers -5 and 3, then group1. contains (-5) would return true, and group1. contains (2) would return false. Write the complete NumberGroup interface. It must have exactly one method. Part (b) begins on page 17. C 2015 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -16-[151]Source: ap14_comp_sci_scoring_guidelines.pdf+1 Declares appropriate private instance variables +2 Implements constructor +1 public Trio (Sandwich sandwich, Salad salad, Drink drink) +1 Initializes appropriate instance variables using parameters +1 Implements interface methods (public String getName ( ) { . . . }, public double getPrice () { . . . }) +1 Constructs correct name string and makes available for return in getName +1 Returns constructed name string in getName +1 Computes correct price and makes available for return in getPrice +1 Returns computed price in getPrice Question-Specific Penalties | | 递归 | Recursion | 递归算法 | 递归函数、递归终止条件 [12]Source: 2024 cs题.pdfCS 扫描全能王 3亿人都在用的扫描App COMPUTER SCIENCE A SECTION II Time-1 hour and 30 minutes 4 Questions Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. You may plan your answers in this orange booklet, but no credit will be given for anything written in this booklet. You will only earn credit for what you write in the separate Free Response booklet. Notes: Unauthorized copying or reuse of any part of this page is illegal. -4- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App NO TEST MATERIAL ON THIS PAGE -5- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 1. This question involves a game in which a player tries to hit a target by throwing a ball. You will write two static methods of the following BallGame class. public class BallGame { / ** Simulates a player throwing the ball in the game and returns a score, as described * in part (a) * / public static int ballThrow() { /* to be implemented in part (a) */ } / ** Simulates a player throwing the ball numThrows times and returns the average of all throws * with scores greater than minScore, as described in part (b) * Precondition: numThrows > 0 * / public static double averageThrow(int numThrows, int minScore) { /* to be implemented in part (b) */ }[26]Source: 2024 cs题.pdfCS 扫描全能王 3亿人都在用的扫描App 21. Consider the following method. public static String doSomething (int current) { if (current <= 0) { return ""; else { return doSomething (current - 2) + current; } } What value is returned as a result of the call doSomething (10) ? (A) "108642" (B) "246810" (C) "0246810" (D) "1086420" (E) *12345678910* Unauthorized copying or reuse of any part of this page is illegal. -25- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 22. Consider the following method, which is intended to print the contents of a two-dimensional array of integers in row-major order. public static void print2DArray (int [] [] table) { for (int a = 0; a < table. length; a++) { for (int b = 0; b < table[0] . length; b++) { System. out. print (table[b] [a] + " "); } System. out. println(); }[38]Source: ap14_comp_sci_scoring_guidelines.pdfThese canonical solutions serve an expository role, depicting general approaches to solution. Each reflects only one instance from the infinite set of valid solutions. The solutions are presented in a coding style chosen to enhance readability and facilitate understanding. C 2014 The College Board. Visit the College Board on the Web: www. collegeboard. org. | | 排序与算法 | Sorting, selection sort, bubble sort | 排序算法 | 选择排序、嵌套循环 [27]Source: 2024 cs题.pdf15. Consider a method to determine whether two arrays have the same length and same values stored in the same order. public static boolean haveSameContents(int[] arr1, int[] arr2) { /* implementation not shown */ } Consider the following implementations of haveSameContents. I. return (arr1. length == arr2. length) && (arr1 == arr2) ; II. if (arr1. length != arr2. length) { return false; } for (int k = 0; k < arr1. length; k++) { return arr1 [k] == arr2 [k] ; } return true; III. if (arr1. length == arr2. length) { for (int k = 0; k < arr1. length; k++) { if (arr1[k] != arr2 [k] ) { return false; } } return true; } return false; Which of the implementations can be used so that haveSameContents will work as intended? (A) I only (B) II only (C) III only (D) I and III (E) II and III Unauthorized copying or reuse of any part of this page is illegal. -18- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App[28]Source: 2024 cs题.pdf/ / There may be instance variables, constructors, and methods that are not shown. } (a) Write the ballThrow method, which simulates a player throwing a ball one time. The method returns a score of 10, 20, 30, 40, or 50. The score is randomly generated, with each score having an equal chance of being returned. Complete method ballThrow. / ** Simulates a player throwing the ball in the game and returns a score, as described in part (a) * / public static int ballThrow() Begin your response at the top of a new page in the Free Response booklet and fill in the appropriate circle indicating the question number. If there are multiple parts to this question, write the part letter with your response. Unauthorized copying or reuse of any part of this page is illegal. -6- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App (b) Write the averageThrow method, which simulates a player throwing the ball numThrows times and returns the average of all throws with scores greater than minScore. If none of the throws have a score greater than minScore, then the averageThrow method returns 0. 0. The following table represents four calls to averageThrow and the possible results. Call to averageThrow Possible Results Generated by ballThrow Value Returned by averageThrow Explanation BallGame. averageThrow(3, 10) 30, 40, 50 40. 0 The average of 30, 40, and 50 | | 搜索/查找 | Search, linear search, binary search | 查找算法 | 顺序查找、二分查找等 [97]Source: ap13_comp_sci_a_scoring_guidelines.pdf-1 (g) Uses getLength/getSize for ArrayList size -2 (v) Consistently uses incorrect array name instead of downloadList/titles -1 (z) Attempts to return a value from updateDownloads @ 2013 The College Board. Visit the College Board on the Web: www. collegeboard. org. AP® COMPUTER SCIENCE A 2013 CANONICAL SOLUTIONS Question 1: SongList Part (a): public DownloadInfo getDownloadInfo (String title) { for (DownloadInfo info : downloadList) { if (info. getTitle () . equals (title) ) { return info; } } return null;[126]Source: ap-computer-science-a-frq-2017.pdf-16- 2017 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS Complete method findPosition below. / ** Returns the position of num in intArr; * returns null if no such element exists in intArr. * Precondition: intArr contains at least one row. * / public static Position findPosition (int num, int [] [] intArr) Part (b) begins on page 18. @ 2017 The College Board. Visit the College Board on the Web: www. collegeboard. org. | | 二维数组 | 2D Array | 二维数组 | 行优先/列优先遍历 [4]Source: ap16_frq_computer_science_a.pdfGO ON TO THE NEXT PAGE. -10- AP® AP® Computer Science A 2016 Free-Response Questions @ 2016 The College Board. College Board, Advanced Placement Program, AP, AP Central, and the acorn logo are registered trademarks of the College Board. Visit the College Board on the Web: www. collegeboard. org. AP Central is the official online home for the AP Program: apcentral. collegeboard. org. CollegeBoard 2016 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS COMPUTER SCIENCE A SECTION II Time-1 hour and 30 minutes Number of questions-4 Percent of total score-50[103]Source: ap13_frq_comp_sci.pdf* @param startRow the first row index of the section * @param endRow the last row index of the section * @param startCol the first column index of the section * @param endCol the last column index of the section * Precondition: 0 <= startRow <= endRow < view. length * Precondition: 0 <= startCol <= endCol < view [ 0] . length * @return the average of the values in the specified section of view * / public double getAverage (int startRow, int endRow, int startCol, int endCol) STOP END OF EXAM | | 数学与逻辑表达式| Modulo, integer division, &&, ||, ! | 数学和逻辑表达式 | 取余、整除、关系运算 [21]Source: ap15_frq_computer_science_a.pdf-15- 2015 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS 4. This question involves the design of an interface, writing a class that implements the interface, and writing a method that uses the interface. (a) A number group represents a group of integers defined in some way. It could be empty, or it could contain one or more integers. Write an interface named NumberGroup that represents a group of integers. The interface should have a single contains method that determines if a given integer is in the group. For example, if group1 is of type NumberGroup, and it contains only the two numbers -5 and 3, then group1. contains (-5) would return true, and group1. contains (2) would return false. Write the complete NumberGroup interface. It must have exactly one method. Part (b) begins on page 17. C 2015 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -16-[20]Source: ap16_frq_computer_science_a.pdf2016 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS 4. This question involves the process of taking a list of words, called wordList, and producing a formatted string of a specified length. The list wordList contains at least two words, consisting of letters only. When the formatted string is constructed, spaces are placed in the gaps between words so that as many spaces as possible are evenly distributed to each gap. The equal number of spaces inserted into each gap is referred to as the basic gap width. Any leftover spaces are inserted one at a time into the gaps from left to right until there are no more leftover spaces. The following three examples illustrate these concepts. In each example, the list of words is to be placed into a formatted string of length 20. Example 1: wordList: [ "AP", "COMP", "SCI", "ROCKS" ] Total number of letters in words: 14 Number of gaps between words: 3 Basic gap width: 2 Leftover spaces: 0 Formatted string: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 A P COM P S CI | | 异常与边界 | Exception, bounds checking | 异常处理与越界 | 下标越界、空指针 [32]Source: ap16_frq_computer_science_a.pdfClass information for this question public class StringFormatter public static int totalLetters (List<String> wordList) public static int basicGapWidth (List<String> wordList, int formattedLen) public static int leftoverSpaces (List<String> wordList, int formattedLen) public static String format (List<String> wordList, int formattedLen) WRITE YOUR SOLUTION ON THE NEXT PAGE. @ 2016 The College Board. Visit the College Board on the Web: www. collegeboard. org. GO ON TO THE NEXT PAGE. -22- 2016 AP® COMPUTER SCIENCE A FREE-RESPONSE QUESTIONS[52]Source: 2024 cs题.pdf(C) 2 (D) 3 (E) 4 Unauthorized copying or reuse of any part of this page is Illegal. -7- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App 4. Consider the following code segment. Assume that x and y are properly declared and initialized integer variables. int z = 0; if (x < y) { if (x > 0) { Z = 10; } else { } z = 20; Under which of the following conditions is the variable z set to 20 ? (A) Whenever x is less than y (B) Whenever x is less than or equal to 0 (C) Whenever x is less than y and x is not greater than 0 (D) Whenever y is less than or equal to x (E) Whenever z is not set to 10 Unauthorized copying or reuse of any part of this page is illegal. -8- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App | | 深浅拷贝 | Deep Copy, Shallow Copy | 深拷贝/浅拷贝 | 对象引用与new的区别 [27]Source: 2024 cs题.pdf15. Consider a method to determine whether two arrays have the same length and same values stored in the same order. public static boolean haveSameContents(int[] arr1, int[] arr2) { /* implementation not shown */ } Consider the following implementations of haveSameContents. I. return (arr1. length == arr2. length) && (arr1 == arr2) ; II. if (arr1. length != arr2. length) { return false; } for (int k = 0; k < arr1. length; k++) { return arr1 [k] == arr2 [k] ; } return true; III. if (arr1. length == arr2. length) { for (int k = 0; k < arr1. length; k++) { if (arr1[k] != arr2 [k] ) { return false; } } return true; } return false; Which of the implementations can be used so that haveSameContents will work as intended? (A) I only (B) II only (C) III only (D) I and III (E) II and III Unauthorized copying or reuse of any part of this page is illegal. -18- GO ON TO THE NEXT PAGE. CS 扫描全能王 3亿人都在用的扫描App | | API文档与规范 | Java Quick Reference, Documentation | Java 快速参考 | 按规范调用标准库方法 [11]Source: 2025年AP计算机科学A北美FRQ .pdfAP® AP Computer Science A Free-Response Questions AP COMPUTER SCIENCE A 2025 - FREE-RESPONSE QUESTIONS COMPUTER SCIENCE A SECTION II TIME - 1 HOUR AND 30 MINUTES Directions: Section II has 4 free-response questions and lasts 1 hour and 30 minutes. All program segments must be written in Java. Show all your work. Credit for partial solutions will be given. Java Quick Reference information can be accessed in this application and is available throughout the exam. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit.[34]Source: ap14_comp_sci_scoring_guidelines.pdf} } return count; } These canonical solutions serve an expository role, depicting general approaches to solution. Each reflects only one instance from the infinite set of valid solutions. The solutions are presented in a coding style chosen to enhance readability and facilitate understanding. c 2014 The College Board. Visit the College Board on the Web: www. collegeboard. org. AP® COMPUTER SCIENCE A 2014 SCORING GUIDELINES Question 4: Trio Class: Trio 9 points Intent: Define implementation of MenuItem interface that consists of sandwich, salad, and drink +1 public class Trio implements MenuItem |
常见核心terms短语补充(按领域)
- 集合类: add, remove, get, size, clear
- 字符串: length, charAt, substring, replace, equals
- 数组/列表遍历: for-each loop, index-based loop
- OOP: field, method, constructor, inheritance, overriding, polymorphism, interface, abstract
- 异常处理: try-catch, NullPointerException, IndexOutOfBoundsException
- 算法: merge, swap, compare, sort, search, inversion
温馨建议:
- 高频考点最常出现在填空、完型、简答题、完整程序编写等类型。
- 真题里对象设计题、接口实现题、数组/字符串处理题、嵌套循环和递归题一定要熟练。
- 这些术语都要能看懂题干、理解选择题选项,写程序时兼顾命名和风格。
有什么概念/考试内容不熟悉,都可以让我帮你加强记忆、举例或练习!也可以帮你生成知识点专属记忆卡!
苡甜甜甜,你好!你提到集合没学好,下面我会用AP真题中的经典考点+详细讲解+例题解析的方式,帮你把集合List/Set/Map以及常考操作讲透。你可以直接用表格预览、再看例题细节和总结。
一、AP考试中常见集合类型与操作【中英对照】
| 英文名 | 中文名 | 常考操作 | 示例构造/说明 | |:--------------|:------------|:----------------------------|:-----------------------------| | List/ArrayList| 列表/动态数组| add、remove、get、set、size | ArrayList<String> list = new ArrayList<>(); | | Set/HashSet | 集合(无重复)| add、remove、contains、size | Set<Integer> set = new HashSet<>(); | | Map/HashMap | 映射/字典 | put、get、containsKey、remove| Map<String, Integer> map = new HashMap<>(); |
【1】List/ArrayList(有序/可重复)讲解
- 基本用法:存一组有序元素,元素可以重复。常用下标访问。
- 核心操作
add(element): 增加元素remove(index)或remove(object): 删除元素get(index): 取某个位置set(index, value): 修改某个位置size(): 长度
【真题例子】
- 2013年FRQ题型:
public void updateDownloads(List<String> titles) {
for (String title : titles) {
DownloadInfo found = getDownloadInfo(title);
if (found == null) {
downloadList.add(new DownloadInfo(title));
} else {
found.incrementTimesDownloaded();
}
}
}
【考点】
【2】Set/HashSet(无序/无重复)讲解
- 概念:集合不能有重复元素,不能按下标访问,只能按元素找。
- 常用操作
add(element): 添加且自动去重contains(element): 查是否在集合中remove(element): 移除指定元素size(): 集合元素数量
【真题情景分析】
- AP题有时考查如何判断某个值在不在某组、无重复自动去重。
【3】Map/HashMap(键-值对)讲解
- 概念:key-value映射,key唯一,value可重复,可以根据key高效查找。
- 常用操作
put(key, value): 新增/修改键-值对get(key): 根据key查找remove(key): 根据key移除containsKey(key): 判断某个key在不在
【真题例子】
- 如果需要统计某元素出现次数(如字符串统计或投票问题),常用Map。
二、典型真题例子讲解
1. 查找与插入(List)
【例题】(简化)
ArrayList<Integer> nums = new ArrayList<>();
nums.add(1); nums.add(2); nums.add(3);
// 查找并增加
if (!nums.contains(5)) {
nums.add(5); // 只加不重复的
}
【考点】
- 遍历、判重插入(虽List可以重复,这里用contains避免)。
2. 元素统计(Map)
【例题】
Map<String, Integer> voteCount = new HashMap<>();
for (String vote : votes) {
voteCount.put(vote, voteCount.getOrDefault(vote, 0) + 1);
}
【考点】
- Map自动创建和计数,key作为唯一标识,适合投票/词频等题。
3. 去重判定(Set)
【例题】
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
boolean hasDuplicate = set.size() != nums.length;
【考点】
- 利用Set自动去重,size变化判断重复。
三、真题技巧与易错点
- 遍历List删除元素:用
Iterator或倒序,否则容易漏删/越界。 - 避免NullPointerException:Map用
containsKey判断再get。 - 区分List/Set/Map特性:List能存重复元素,Set不能,Map按键查找。
四、真题秒杀小练
1. 判断一个int数组是否有重复元素?
Set<Integer> set = new HashSet<>();
for(int num : nums){
if(!set.add(num)){
return true; // 有重复
}
}
return false;
2. 将String数组所有单词统计出现次数?
Map<String, Integer> map = new HashMap<>();
for(String s : arr){
map.put(s, map.getOrDefault(s, 0) + 1);
}
五、你还需要重点掌握的常见术语(关键字对照)
| 英文 | 中文 | 含义 |
|---|---|---|
| add | 添加 | 向集合增加元素 |
| get | 获取 | 按下标/Key取元素 |
| remove | 移除 | 删除元素 |
| contains | 包含 | 集合中是否有某元素 |
| put | 新增映射 | Map中放入键-值对 |
| size | 长度 | 集合元素数量 |
★有具体某道题不会、某份试卷卡住,直接发出来,我帮你一步一步讲解代码思路和集合操作怎么用!
随时加深理解、可以反复问我哦!相信你能掌握集合击穿AP!
Ask Sia for quick explanations, examples, and study support.