Game
is #1 from the from the 2022 AP Computer Science A Free Response problems.
https://apcentral.collegeboard.org/pdf/ap22-frq-computer-science-a.pdf?course=ap-computer-science-a
Part (a) getScore
method
public int getScore()
{
int score = 0;
if(levelOne.goalReached())
{
score += levelOne.getPoints();
if(levelTwo.goalReached())
{
score += levelTwo.getPoints();
if(levelThree.goalReached())
{
score += levelThree.getPoints();
}
}
}
if(isBonus())
score *= 3;
return score;
}
Part (b) playManyTimes
method
public int playManyTimes(int num)
{
play();
int bestScore = getScore();
for(int g = 2; g <= num; g++)
{
play();
int score = getScore();
if(score > bestScore)
bestScore = score;
}
return bestScore;
}
This is a standard find the max problem. The code above follows the advice at finding the minimum or maximum and starts bestScore
at the first value that could be the maximum. The loop runs num - 1
times, since the first game has been played before the loop.
2022 AP CS Exam Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn