a. Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
b. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied.
c. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit.
This question uses two classes: an Item class that represents an item that has a name and value and an ItemGrid class that manages a two-dimensional array of items. A definition of the Item class is shown below.
public class Item
{
private String name;
private int value;
public Item(String itemName, int itemValue)
{
name = itemName;
value = itemValue;
}
public String getName()
{
return name;
}
public int getValue()
{
return value;
}
}
The ItemGrid class below uses the two-dimensional array grid to represent a group of Item objects.
public class ItemGrid
{
private Item[][] grid;
// Constructor not shown
/** Returns true if xPos is a valid row index and yPos is a valid
* column index and returns false otherwise.
*/
public boolean isValid(int xPos, int yPos)
{ /* implementation not shown */ }
/** Compares the item in row r and column c to the items to its
* left and to its right. Returns the name of the item with
* the greatest value, as described in part (a).
* Precondition: r and c are valid indices
*/
public String mostValuableNeighbor(int r, int c)
{ /* to be implemented in part (a) */ }
/** Returns the average value of all the items in grid,
* as described in part (b).
*/
public double findAverage()
{ /* to be implemented in part (b) */ }
}
(a) Write the mostValuableNeighbor method, which compares the item in row r and column c to the items to its left and to its right. The method determines which of the three items has the greatest value and returns its name.