Sign
is #2 from the from the 2023 AP Computer Science A Free Response problems.
https://apcentral.collegeboard.org/media/pdf/ap23-frq-comp-sci-a.pdf
Sign
class
public class Sign
{
private String message;
private int lineWidth;
public Sign(String message, int lineWidth)
{
this.message = message;
this.lineWidth = lineWidth;
}
public int numberOfLines()
{
int lines = message.length() / lineWidth;
if(message.length() % lineWidth > 0)
lines++;
return lines;
}
public String getLines()
{
if(message.length() == 0)
return null;
String lines = "";
String messageRemaining = message;
while(messageRemaining.length() > lineWidth)
{
lines += messageRemaining.substring(0, lineWidth);
lines += ";";
messageRemaining = messageRemaining.substring(lineWidth);
}
lines += messageRemaining;
return lines;
}
}
As an alternative to storing message
and lineWidth
, it is possible to store the number of lines and the String
representing the formatted lines.
See Class writing order for a technique to respond to AP CS FR that request an entire class.
See Strings on the AP CS A Exam for detailed examples of calls to substring
.
Java files with test code
TwoTest.java includes JUnit 5 test code with the examples from the problem. See Running JUnit 5 tests.
2023 AP CS Exam Free Response Solutions
- AppointmentBook Free Response Solution
- WeatherData Free Response Solution
- BoxOfCandy Free Response Solution
Help & comments
Get help from AP CS Tutor Brandon Horn