为什么这是无限循环
Why is this infinite loop
抱歉,这可能是新手问题。但这是我讲师的作业,截止日期是明天。我尝试了很多方法并跟踪输出,但它仍然导致无限循环。请帮忙。
提问的问题:
Remove the passed students from studentList and move them to a new 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。您的帮助将不胜感激。非常感谢。
根据代码,您正在分配 StudentLinkedList failList = studentList;
。这不会创建 studentList
的副本,也不会分配新内存,而是意味着 failList
指向 studentList
.
所以在 failList
中所做的任何更改实际上都在 studentList
中更改。
这可以解释为什么当它击中失败的学生时会出现无限循环,因为您实际上只是将学生添加回初始 studentList
而不是新创建的 failList
如预期。
抱歉,这可能是新手问题。但这是我讲师的作业,截止日期是明天。我尝试了很多方法并跟踪输出,但它仍然导致无限循环。请帮忙。
提问的问题:
Remove the passed students from studentList and move them to a new 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。您的帮助将不胜感激。非常感谢。
根据代码,您正在分配 StudentLinkedList failList = studentList;
。这不会创建 studentList
的副本,也不会分配新内存,而是意味着 failList
指向 studentList
.
所以在 failList
中所做的任何更改实际上都在 studentList
中更改。
这可以解释为什么当它击中失败的学生时会出现无限循环,因为您实际上只是将学生添加回初始 studentList
而不是新创建的 failList
如预期。