public class BoxOfCandy
{
private Candy[][] box;
public BoxOfCandy(int n, int m)
{
box = new Candy[n][m]; // Box is empty
}
public void insertFlavor(int i, int j, String f)
{
box[i][j] = new Candy(f);
}
/**
* Moves one piece of candy in column col, if necessary and possible,
* so that the box element in row 0 of column col contains a piece of candy,
* as described in part (a).
* Returns false if there is no piece of candy in column col and returns
* true otherwise.
* Precondition: col is a valid column index in box.
*/
public boolean moveCandyToFirstRow( int col )
{
if(box[0][col] != null)
return true;
for(int r = 1; r < box.length; r++)
{
if(box[r][col] != null)
{
box[0][col] = box[r][col];
box[r][col] = null;
return true;
}
}
return false;
}
/**
* Removes from box and returns a piece of candy with flavor specified
* by the parameter, or returns null if no such piece is found,
* as described in part (b)
*/
public Candy removeNextByFlavor( String flavor )
{
for(int r = box.length - 1; r >= 0; r--)
{
for(int c = 0; c < box[0].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;
}
public String toString()
{
String s = "";
for( Candy[] r : box )
{
for( Candy c : r )
{
s += c + "\t";
}
s+= "\n";
}
return s;
}
}
|