public class LinkedBagDemo1
1: /** A test of the methods add, toArray, isEmpty, and getCurrentSize,
2: as defined in the first draft of the class LinkedBag.
3: @author Frank M. Carrano, Timothy M. Henry
4: @version 5.0
5: */
6: public class LinkedBagDemo1
7: {
8: public static void main(String[] args)
9: {
10: System.out.println("Creating an empty bag.");
11: BagInterface<String> aBag = new LinkedBag1<>();
12: testIsEmpty(aBag, true);
13: displayBag(aBag);
14:
15: String[] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"};
16: testAdd(aBag, contentsOfBag);
17: testIsEmpty(aBag, false);
18: } // end main
19:
20: // Tests the method isEmpty.
21: // Precondition: If the bag is empty, the parameter empty should be true;
22: // otherwise, it should be false.
23: private static void testIsEmpty(BagInterface<String> bag, boolean empty)
24: {
25: System.out.print("\nTesting isEmpty with ");
26: if (empty)
27: System.out.println("an empty bag:");
28: else
29: System.out.println("a bag that is not empty:");
30:
31: System.out.print("isEmpty finds the bag ");
32: if (empty && bag.isEmpty())
33: System.out.println("empty: OK.");
34: else if (empty)
35: System.out.println("not empty, but it is: ERROR.");
36: else if (!empty && bag.isEmpty())
37: System.out.println("empty, but it is not empty: ERROR.");
38: else
39: System.out.println("not empty: OK.");
40: } // end testIsEmpty
41:
42: // Tests the method add.
43: private static void testAdd(BagInterface<String> aBag, String[] content)
44: {
45: System.out.print("Adding the following strings to the bag: ");
46: for (int index = 0; index < content.length; index++)
47: {
48: if (aBag.add(content[index]))
49: System.out.print(content[index] + " ");
50: else
51: System.out.print("\nUnable to add " + content[index] +
52: " to the bag.");
53: } // end for
54: System.out.println();
55:
56: displayBag(aBag);
57: } // end testAdd
58:
59: // Tests the method toArray while displaying the bag.
60: private static void displayBag(BagInterface<String> aBag)
61: {
62: System.out.println("The bag contains the following string(s):");
63: Object[] bagArray = aBag.toArray();
64: for (int index = 0; index < bagArray.length; index++)
65: {
66: System.out.print(bagArray[index] + " ");
67: } // end for
68:
69: System.out.println();
70: } // end displayBag
72: } // end LinkedBagDemo1
74: /*
75: Creating an empty bag.
76:
77: Testing isEmpty with an empty bag:
78: isEmpty finds the bag empty: OK.
79: The bag contains the following string(s):
80:
81: Adding the following strings to the bag: A D B A C A D
82: The bag contains the following string(s):
83: D A C A B D A
84:
85: Testing isEmpty with a bag that is not empty:
86: isEmpty finds the bag not empty: OK.
87: */