-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCDCollection.java.txt
75 lines (61 loc) · 2.44 KB
/
CDCollection.java.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//********************************************************************
// CDCollection.java Author: Lewis/Loftus
//
// Represents a collection of compact discs.
//********************************************************************
import java.text.NumberFormat;
public class CDCollection
{
private CD[] collection;
private int count;
private double totalCost;
//-----------------------------------------------------------------
// Constructor: Creates an initially empty collection.
//-----------------------------------------------------------------
public CDCollection ()
{
collection = new CD[100];
count = 0;
totalCost = 0.0;
}
//-----------------------------------------------------------------
// Adds a CD to the collection, increasing the size of the
// collection if necessary.
//-----------------------------------------------------------------
public void addCD (String title, String artist, double cost,
int tracks)
{
if (count == collection.length)
increaseSize();
collection[count] = new CD (title, artist, cost, tracks);
totalCost += cost;
count++;
}
//-----------------------------------------------------------------
// Returns a report describing the CD collection.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nCD List:\n\n";
for (int cd = 0; cd < count; cd++)
report += collection[cd].toString() + "\n";
return report;
}
//-----------------------------------------------------------------
// Increases the capacity of the collection by creating a
// larger array and copying the existing collection into it.
//-----------------------------------------------------------------
private void increaseSize ()
{
CD[] temp = new CD[collection.length * 2];
for (int cd = 0; cd < collection.length; cd++)
temp[cd] = collection[cd];
collection = temp;
}
}