Answered step by step
Verified Expert Solution
Question
1 Approved Answer
import java.util.ArrayList; / * * * Class Safe - simulates the behavior of a real safe. * * This class interacts with the SafeState class
import java.util.ArrayList;
Class Safe simulates the behavior of a real safe.
This class interacts with the SafeState class to model the functionality of a safe,
allowing users to perform actions such as opening and locking the safe.
@author Simon Pyne
@version
public class Safe
Private fields
private SafeState state; Controls the state of the safe
private int maxItems; Maximum number of items that can be stored in the safe
Public field for testing purposes
public ArrayList contents; Keeps a record of items in the safe
Constructor for objects of class Safe.
Initializes the SafeState and sets the maximum number of items to a default value.
public Safe
this; Call the other constructor with a default value for maxItems
Constructor for objects of class Safe with a specified maximum number of items.
@param aMaxItems The maximum number of items the safe can hold.
public Safeint aMaxItems
state new SafeState;
maxItems aMaxItems;
contents new ArrayList;
Add an item to the safe contents if the safe is not full.
@param item The item to be added to the safe.
public void addToContentsString item
if contentssize maxItems
contents.additem;
If the safe is full, do nothing
Remove an item from the safe contents if it exists.
@param item The item to be removed from the safe.
public void removeFromContentsString item
if contentscontainsitem
contents.removeitem;
System.out.printlnRemoved item";
else
System.out.printlnItem item not in safe";
Display all items currently stored in the safe contents.
public void display
for String item : contents
System.out.printlnitem;
Remove all items from the safe, one at a time.
Prints "Removed item" after each item is removed.
public void empty
while contents.isEmpty
String removedItem contents.remove;
System.out.printlnRemoved item: removedItem;
Attempt to open the safe using a provided code.
@param code The code to attempt to open the safe.
@return True if the safe is now open, false otherwise.
public boolean openString code
return state.opencode;
Attempt to lock the safe using a provided code.
@param code The code to attempt to lock the safe.
@return True if the safe is now locked, false otherwise.
public boolean lockString code
return state.lockcode;
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started