【问题标题】:Why is this infinite loop为什么这个无限循环
【发布时间】:2020-08-08 17:56:31
【问题描述】:

对不起,也许这是一个新手问题。但这是我的讲师的作业,截止日期是明天。我尝试了很多方法并跟踪输出,但它仍然导致无限循环。请帮忙。

问的问题:

从studentList中移除通过的学生,并将他们移动到一个新的LinkedList passList

主要应用:

StudentLinkedList failList = studentList; //assume studentList is already existed with some data
StudentLinkedList passList = new StudentLinkedList();

Student s = (Student)studentList.removeFirst(); //the return type was Object (it was user-defined LinkedList)
//so i use dynamic binding to change it to student
while(s != null) {
  if(s.isPass()) { //return true if student passed
    System.out.println("pass"); //i track my output with this
    passList.addFirst(s);
  } else {
    System.out.println("fail"); //track output
    failList.addFirst(s);
  }
  s = (Student)studentList.removeFirst();
}

输出是失败和通过之间的无限循环,我认为循环是因为 s 从不为空。

这里删除第一个方法定义:

public Object removeFirst() {
   if(head == null) { //check if the list was empty
     return null;
   } else {
     current = head;
     head = head.next;
     if(head == null) {
        tail = null;
     }
     return current.element;
   }
}

我正在学习 Java 的第二年。您的帮助将不胜感激。非常感谢。

【问题讨论】:

  • 尝试在每次调用.removeFirst() 函数时输出s 是什么,这样您就可以看到它是什么以及为什么它不等于null。另外,不确定new StudentLinkedList; 是否会输出您期望的结果。
  • @ruakh 很抱歉,当我尝试添加评论时输入错误,我一定是不小心删除了 ()。我已经修好了。问题还是一样。
  • @Ryan 我已经添加了你在s 之后提出的问题,结果它打印了列表中第一个失败的学生的无限循环。 removeFirst() 定义有问题吗?
  • 非常欢迎新手问题,只要它们经过充分研究和解释。你的很好。
  • 使用迭代器模式并尽量避免while循环。如果“s”是对象,那么不要担心内存,也不要从学生列表中删除学生——只需遍历学生,并创建两个额外的列表。对于未来 - isPass() 不应该是 Student 对象的一部分,应该有额外的对象 StudentResult 并且结果计算应该在单独的无状态组件中完成。

标签: java loops while-loop linked-list infinite-loop


【解决方案1】:

从代码中,您分配了StudentLinkedList failList = studentList;。这不会创建studentList 的副本并且不会分配新内存,而是意味着failList 指向studentList

因此,在failList 中所做的任何更改实际上都会在studentList 中进行更改。

这可以解释为什么在遇到失败的学生时会出现无限循环,因为您实际上只是将学生添加回最初的studentList,而不是按预期新创建的failList

【讨论】:

  • 成功了!我使用 while 循环将每个数据复制到另一个列表。糟糕的是,我真的忘记了,即使是我的讲师去年也教过我。非常感谢!作为一名学生,我会记住不要只是简单地分配像a = b; 这样将来复制一些东西。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2016-07-27
  • 2021-08-16
  • 2018-01-13
  • 1970-01-01
相关资源
最近更新 更多