AP Computer Science A 2025 – Free-Response Question 2: SignedText Class

2025 AP® Computer Science A Free-Response Questions

Question 2: SignedText Class

Context

This question involves the SignedText class, which contains methods used to include a signature as part of a string of text. You will write the complete SignedText class, which contains a constructor and two methods.

The SignedText constructor takes two String parameters: a first name and a last name. The length of the last name is always greater than or equal to 1.

The getSignature method takes no parameters and returns a formatted signature string constructed from the first and last names according to the following rules:

  • If the first name is an empty string, the returned signature contains only the last name.
  • If the first name is not empty, the returned signature is:
    • the first letter of the first name
    • a dash "-"
    • the last name

The addSignature method returns a possibly revised copy of its String parameter. The parameter contains at most one occurrence of the object's signature, at either the beginning or the end of the string.

The returned string follows these rules:

  • If the signature does not occur in the parameter, return the parameter with the signature appended to the end.
  • If the signature occurs at the end, return the parameter unchanged.
  • If the signature occurs at the beginning, remove it from the beginning and append it to the end.

Sample Code Execution

The following table shows example usage:

Statement Method Call Return Value Explanation
SignedText st1 = new SignedText("", "Wong"); st1 has an empty first name and last name "Wong".
String temp = st1.getSignature(); st1.getSignature() "Wong" First name empty → return only last name.
SignedText st2 = new SignedText("henri", "dubois"); st2 has first name "henri" and last name "dubois".
temp = st2.getSignature(); st2.getSignature() "h-dubois" First letter of first name + "-" + last name.
SignedText st3 = new SignedText("GRACE","LOPEZ"); st3 has first name "GRACE" and last name "LOPEZ".
temp = st3.getSignature(); st3.getSignature() "G-LOPEZ" First letter uppercase → "G-LOPEZ".
SignedText st4 = new SignedText("", "FOX"); st4 has empty first name and last name "FOX".
String text = "Dear"; st4.addSignature(text) "DearFOX" No signature in text → append to end.
text = "Best wishesFOX"; st4.addSignature(text) "Best wishesFOX" Signature at end → return unchanged.
text = "FOXThanks"; st4.addSignature(text) "ThanksFOX" Signature at beginning → remove it and append to end.
text = "G-LOPEZHello"; st3.addSignature(text) "HelloG-LOPEZ" Signature at beginning → move to end.

Task

Write the complete SignedText class so that it behaves exactly as described and matches the sample executions.

Student Code Submission Form

Paste your code into the box below and submit it to Mr. Crow for review/feedback.

"

Contact form