Reputation: 13
The while loop should compare the ibsn's of these two objects. Objects being compared:
list[0] = new ReadingMatter ("Words and Stuff", "9-082-1090-1");
list[1] = new Magazine ("Fashion", "318921019", "Mike Dales");
list[2] = new Book ("Rocks and Minerals", "3-323-0691-2", "Jamie Dawson");
String[] mainCharacters = {"Lennie","George","Candy"};
list[3] = new Novel ( "Of Mice and Men", "4-569-2190-1", "John Steinbeck", mainCharacters);
list[4] = new TextBook ("Java, Java, Java", "3-131-9871-0", "John Smith", true);
the changed compareTo:
public int compareTo(Object other)
{
ReadingMatter temp = (ReadingMatter)other;
int result = 0;
if (this.isbn.compareTo(temp.getIsbn()) > 0)
result = -1;
else if (this.isbn.compareTo(temp.getIsbn()) < 0)
result = 1;
return result;
}
the while loop
while(testing)
{
testing = false;
for(int j = 0; j < list.length - 1; j++)
{
if (list[j].compareTo(list[j+1]) > 0)
{
temp = list[0];
list[0] = list[1];
list[1] = temp;
testing = true;
}
}
}
is it something to do with the hyphenated numbers? how would i get around the hyphens?
EDIT: The problem is that the loop is infinite, the if statement is always being used
Upvotes: 0
Views: 154
Reputation: 11849
Since your conditional only orders elements 0
and 1
, you will end up with list[0] < list[1] < list[2]
which sets testing=true
and loops, again.
Upvotes: 0
Reputation: 9201
The problem is that you always switching index 0 and 1 but checking index j and j+1:
if (list[j].compareTo(list[j+1]) > 0)
{
temp = list[0];
list[0] = list[1];
list[1] = temp;
testing = true;
}
Therefore if you have one indexpair j
, j+1
with j>2 to which compareTo
delivers >0 you get your infinite loop.
Upvotes: 1