I saw a similar problem to this, but couldn't understand the solution the guy used. I have to sort this tunes program in order by title. It seems like there is a problem with my sort algorithm, but I cannot figure it out. Here are the classes.
public class Tunes{
public static void main(String[] args) {
CDCollection music = new CDCollection();
music.addCD("Storm Front", "Billy Joel", 14.95, 10);
music.addCD("Come On Over", "Shania Twain", 14.95, 16);
music.addCD("Soundtrack", "Les Mirables", 17.95, 33);
music.addCD("Graceland", "Paul Simon", 13.90, 11);
System.out.println(music);
music.addCD("Double Live", "Garth Brooks", 19.99, 26);
music.addCD("Greatest Hits", "Jimmy Buffet", 15.95, 13);
System.out.println(music);
}
}
----------------------------
import java.text.NumberFormat;
public class CDCollection {
private CD[] collection;
private int count;
private double totalCost;
public CDCollection()
{
collection = new CD[100];
count = 0;
totalCost = 0.0;
}
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++;
}
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "----------------------------------------\n";
report += "My CD Collection\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";
Sort.selectionSort(collection);
for(int i = 0; i<collection.length;i++)
report+=collection[i];
return report;
}
private void increaseSize ()
{
CD[] temp = new CD[collection.length *2];
for (int cd = 0; cd < collection.length;cd++)
temp[cd] = collection[cd];
collection = temp;
}
}
-------------------------
import java.text.NumberFormat;
public class CD implements Comparable
{
private String title, artist;
private double cost;
private int tracks;
public CD (String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
cost = price;
tracks = numTracks;
}
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(cost) + "\t" + tracks + "\t";
description +=title + "\t" + artist;
return description;
}
public boolean equals (CD other)
{
return(title.equals(other.getTitle()));
}
public int compareTo(Object other) {
int result;
String otherTitle = ((CD)(other)).getTitle();
result = title.compareTo(otherTitle);
return result;
}
public String getTitle()
{
return title;
}
}
----------------------------
public class Sort {
public static void selectionSort (CD[] list)
{
int min;
CD temp;
for (int index = 0; index <list.length-1; index++)
{
min = index;
for(int scan = index+1; scan<list.length; scan++)
if(list[scan].compareTo(list[min])<0)
min = scan;
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
}