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,但检查索引 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>2,其中 compareTo
提供 >0,您就会陷入无限循环.
关于java - 无限 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120616/