35.9k views
5 votes
Add new constructors to the Pantry Class: a constructor that takes one Jam parameter, and another that takes two Jam parameters. Unused instance variables in the Pantry object will be set to null.

Now modify the methods of the class to deal with null instance variables: toString() will test for null before appending a String for a Jam. select() will have a return type of boolean. Return true if the selection is available, otherwise false.

Here is a PantryTester2 class that demonstrates the new code:


public class PantryTester2
{
public static void main ( String[] args )
{
Jam goose = new Jam( "Gooseberry", "7/4/86", 12 );
Jam apple = new Jam( "Crab Apple", "9/30/99", 8 );

Pantry hubbard = new Pantry( goose, apple );
hubbard.print();

if ( hubbard.select(1) )
hubbard.spread(2);
else
System.out.println("Selection not available");
System.out.println( hubbard );

if ( hubbard.select(3) )
hubbard.spread(5);
else
System.out.println("Selection not available");
System.out.println( hubbard );

}
}
When it is run, it prints the following:
1: Gooseberry 7/4/86 12 fl. oz.
2: Crab Apple 9/30/99 8 fl. oz.
Spreading 2 fluid ounces of Gooseberry
1: Gooseberry 7/4/86 10 fl. oz.
2: Crab Apple 9/30/99 8 fl. oz.
Selection not available
1: Gooseberry 7/4/86 10 fl. oz.
2: Crab Apple 9/30/99 8 fl. oz.

User Busturdust
by
8.0k points

1 Answer

4 votes

The updated Pantry class includes constructors for one or two Jam parameters, handles null instance variables, and modifies methods. PantryTester2 demonstrates proper functionality by selecting jars and spreading jam.

To achieve the desired functionality, you need to modify the Pantry class by adding new constructors and updating the methods as specified. Here's the modified Pantry class:

class Pantry

{

private Jam jar1;

private Jam jar2;

// Default constructor

public Pantry()

{

jar1 = null;

jar2 = null;

}

// Constructor with one Jam parameter

public Pantry(Jam jar)

{

jar1 = jar;

jar2 = null;

}

// Constructor with two Jam parameters

public Pantry(Jam jar1, Jam jar2)

{

this.jar1 = jar1;

this.jar2 = jar2;

}

// Other methods remain the same

// Method to print the pantry

public void print()

{

System.out.println("1: " + jar1);

System.out.println("2: " + jar2);

}

// Method to select a jar

public boolean select(int jarNumber)

{

if (jarNumber == 1)

return (jar1 != null);

else if (jarNumber == 2)

return (jar2 != null);

else

return false;

}

// Method to spread jam

public void spread(int oz)

{

if (select(1))

jar1.spread(oz);

else if (select(2))

jar2.spread(oz);

}

// Method to convert to string

public String toString()

{

String result = "";

if (jar1 != null)

result += "1: " + jar1 + "\\";

if (jar2 != null)

result += "2: " + jar2 + "\\";

return result;

}

}

With these changes, the PantryTester2 class should work as expected, dealing with null instance variables and returning true or false for the select() method.

User Dylan Wheeler
by
8.5k points