/** Halloween.java -- Here's one application that can make use of a bag. * Let's go trick-or-treating (collect candy names from an input file), * and eat (print) 3 at random. */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class Halloween { public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileInputStream("candy.txt")); BagArrayList bag = new BagArrayList(); // read the input file to intialize the bag while (inFile.hasNextLine()) { String name = inFile.nextLine(); if (name == null) break; bag.add(new Item(name)); } // Now eat 3 at random. We call the remove() function with no parameter, // which means it's the one that selects one object at random. for (int i = 0; i < 3; ++i) { Item candy = bag.remove(); System.out.println("Eating a(n) " + candy); } // Now let's test some other bag methods. System.out.println("Bag size is now " + bag.size()); System.out.println("Contents of bag:\n" + bag); // If we haven't done so already, eat the apple. Item apple = bag.remove(new Item("apple")); if (apple == null) System.out.println("No apple left to eat."); else System.out.println("Eating apple."); System.out.println("Now the bag contains\n" + bag); } }