java - 无限 While 循环

标签 java

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;   
}

因此,如果您有一个索引对 jj+1 和 j>2,其中 compareTo 提供 >0,您就会陷入无限循环.

关于java - 无限 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120616/

相关文章:

java - date.getTime() 比 System.getCurrentTimeMillis() 短

java - Java bean 的 setter 允许返回这个吗?

java - 延迟阴影在LWJGL中到底如何工作?

java - Gwt编译错误: unable to find type

java - JTable 内容和数据库表在一份报告中

java - RecyclerView Adapter 在奇怪的位置插入行

java - 允许 Java 以 main() 结束,而不关闭已执行的进程

java - 如何从java类中调用fragment方法?

javascript - 如何使用 CodeMirror 在 TextArea 中添加值

java - 在 Spring 中继续获取 java.lang.NoClassDefFoundError