Create a generic class with a type parameter that simulates drawing an item at random out of a box. For example, the box might contain Strings representing names written on slips of paper, or the box might contain Integers representing the possible numbers for a lottery draw. Include the following methods:
add() – that allows the user to add an object of the specified type to the box
isEmpty() – to determine if the box is empty
drawItem() – to randomly select an object from the box and return it, as well as eliminating it from the box (if the box is empty return null)
toString() – to output the current contents of the box
In the driver, create two boxes, one with the names of 5 people and one with numbers between 1 and 5 that represent seating at a table. Use the drawItem() method to determine which seat a person will occupy.
Thanks for the question. Here is the completed code for this problem. Comments are included so that you understand whats going on. Let me know if you have any doubts or if you need anything to change. Thank You !! Please do up Vote : ) ======================================================================================== import java.util.ArrayList; import java.util.Random; //Create a generic class with a type parameter public class Items<T> { private ArrayList<T> items; public Items() { items = new ArrayList<T>(); } //add() – that allows the user to add an object of the specified type to the box public void add(T anItem) { items.add(anItem); } //to randomly select an object from the box and return it, // as well as eliminating it from the box public T drawItem() { if (items.size() != 0) { Random random = new Random(); int randomIndex = random.nextInt(items.size()); T drawnItem = items.get(randomIndex); items.remove(randomIndex); return drawnItem; } else { // (if the box is empty return null) return null; } } public boolean isEmpty() { return items.size() == 0; } //toString() – to output the current contents of the box @Override public String toString() { String description = "Items:\n"; for (T item : items) { description += item.toString() + "\n"; } return description; } }
========================================================================================
public class ItemDemo { public static void main(String[] args) { Items<String> boxOne = new Items<String>(); boxOne.add("Jason"); boxOne.add("Jacob"); boxOne.add("Jewel"); boxOne.add("Jane"); boxOne.add("Jackie"); Items<Integer> boxTwo = new Items<Integer>(); for (int i = 1; i <= 5; i++) boxTwo.add(i); while (!boxOne.isEmpty()) { //Use the drawItem() method to determine which seat a person will occupy. String person = boxOne.drawItem(); int seat = boxTwo.drawItem(); System.out.println(person + " will take seat " + seat); } } }
========================================================================================
Get Answers For Free
Most questions answered within 1 hours.