while循环应该比较这两个对象的ibsn。 被比较的对象:
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);
改变后的比较:
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;
}
while循环
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;
}
}
}
是否与带连字符的数字有关?我怎么绕过连字符?
编辑:问题是循环是无限的,if语句总是被使用
答案 0 :(得分:1)
问题是你总是切换索引0和1,但检查索引j和j + 1:
if (list[j].compareTo(list[j+1]) > 0)
{
temp = list[0];
list[0] = list[1];
list[1] = temp;
testing = true;
}
因此,如果你有一个索引对j
,j+1
j {> 1} compareTo
传递&gt; 0,你将获得无限循环。
答案 1 :(得分:0)
由于您的条件仅订阅了元素0
和1
,因此您最终会list[0] < list[1] < list[2]
设置testing=true
并再次循环。