Sign free response problem from the 2023 AP Computer Science A Exam

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.

Mistake? Please comment below.

Java files with test code

TwoTest.java includes JUnit test code with the examples from the problem.

Sign.java
TwoTest.java

2023 AP CS Exam Free Response Solutions

Comments

Comment on Sign