4. The VendingMachine class represents a grid of items stocked in a machine. A partial declaration of the VendingMachine class is shown below.
public class Item
{
/**
* Returns the category of the item (e.g., "Snack", "Drink", "Candy")
*/
public String getCategory()
{ /* implementation not shown */ }
/**
* Returns the price of the item
*/
public double getPrice()
{ /* implementation not shown */ }
/* There may be instance variables, constructors, and methods
that are not shown. */
}public class VendingMachine
{
private Item[][] slots;
/**
* Returns the index of the column containing the greatest number of
* items belonging to the specified category.
* If multiple columns have the same greatest number, the lowest of
* those column indices is returned.
* Preconditions: slots is not null and no elements of slots are null.
* slots has at least one row and at least one column.
*/
public int columnWithMost(String category)
{ /* to be implemented */}
/* There may be instance variables, constructors, and methods
that are not shown. */
}When an element of the two-dimensional array slots is accessed, the first index is used to specify the row and the second index is used to specify the column.
Write the VendingMachine method columnWithMost. The method should return the index of the column in slots that contains the greatest number of items where the category matches the parameter category. If there are multiple columns that are tied for the greatest number of matching items, the lowest index among those columns should be returned.
Suppose slots has the following contents. Each cell displays the category of the Item at that location.
Row | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
0 | "Drink" | "Snack" | "Drink" | "Candy" |
1 | "Drink" | "Snack" | "Snack" | "Candy" |
2 | "Candy" | "Snack" | "Drink" | "Candy" |
Call: columnWithMost("Snack")
Expected Return: should return 1
Explanation: because column 1 contains 3 "Snack" items, which is more than any other column.
Call: columnWithMost("Drink")
Expected Return: should return 0
Explanation: because column 0 and column 2 both contain 2 "Drink" items. Since 2 is the greatest number found and 0 is the lower index, 0 is returned.
Call: columnWithMost("Candy")
Expected Return: should return 3
Explanation: because column 3 contains 3 "Candy" items, which is the maximum for this category.
Complete method columnWithMost.
/**
* Returns the index of the column containing the greatest number of
* items belonging to the specified category.
* If multiple columns have the same greatest number, the lowest of
* those column indices is returned.
* Preconditions: slots is not null and no elements of slots are null.
* slots has at least one row and at least one column.
*/
public int columnWithMost(String category)00:00