# BoxOfCandy free response answer 2023

`BoxOfCandy` is #4 from the from the 2023 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/media/pdf/ap23-frq-comp-sci-a.pdf

## Part (a) `moveCandyToFirstRow` method

``````public boolean moveCandyToFirstRow(int col)
{
if(box[col] != null)
return true;

for(int r = 1; r < box.length; r++)
{
if(box[r][col] != null)
{
box[col] = box[r][col];
box[r][col] = null;
return true;
}
}

return false;
}
``````

## Part (b) `removeNextByFlavor` method

``````public Candy removeNextByFlavor(String flavor)
{
for(int r = box.length - 1; r >= 0; r--)
{
for(int c = 0; c < box.length; c++)
{
if(box[r][c] != null &&
box[r][c].getFlavor().equals(flavor))
{
Candy selected = box[r][c];
box[r][c] = null;
return selected;
}
}
}

return null;
}
``````

I’ve receieved a few comments regarding my use of `box` instead of `box[r]`. This is one of the situations in which I advise students to write code differently on the Exam than they would in a real program. `box` works even if the loop with `c` is the outer loop. `box[r]` doesn’t. In a real program, that would be a compile time error. On the Exam, it could cost a point. On the AP CS A Exam, every row of a 2D array is guaranteed to have the same length.

Candy.java includes a constructor and an implementation of `getFlavor`. FourTest.java includes JUnit test code with the examples from the problem.