Fah*_*adi 0 java infinite-loop
嘿,我有一个程序使用while循环,但我真的很困惑为什么它成为无限循环
这是我的代码
打印无效
public void print() {
DoublyLinkedListNode current = first;
while (current != null) {
current.displayInfo();
current = current.next;
}//end while
}//end print
public DoublyLinkedListNode partition(DoublyLinkedList list,
DoublyLinkedListNode first, DoublyLinkedListNode last) {
DoublyLinkedListNode smallIndex = first;
DoublyLinkedListNode index = smallIndex.next;
DoublyLinkedListNode temp = new DoublyLinkedListNode();
double pivot = first.ipk;
while (index != temp.next) {
if ((index.ipk) < pivot) {
smallIndex = smallIndex.next;
temp.ipk = index.ipk;
index.ipk = smallIndex.ipk;
smallIndex.ipk = temp.ipk;
}
index = index.next;
}
temp.ipk = first.ipk;
first.ipk = smallIndex.ipk;
smallIndex.ipk = temp.ipk;
System.out.println("The list in partition is: ");
list.print();
System.out.print("\n");
return first;
}
public void recQuickSort(DoublyLinkedList list, DoublyLinkedListNode first,
DoublyLinkedListNode last) {
while (first != last) {
DoublyLinkedListNode pivotLocation = partition(list, first, last);
recQuickSort(list, first, pivotLocation.back);
recQuickSort(list, pivotLocation.next, last);
}
}
Run Code Online (Sandbox Code Playgroud)
主要
public static void main(String[] args) {
DoublyLinkedList d = new DoublyLinkedList();
d.insertNode("Apep", "123", 3.5);
d.insertNode("Alex", "121", 3.2);
d.insertNode("Kujul", "124", 3.1);
d.insertNode("Fahmi", "125", 3.7);
d.print();
d.quickSort(d);
d.print();
}
Run Code Online (Sandbox Code Playgroud)
所以从这些代码将有无限循环输出,我不知道哪个来自我的程序,使其无限循环.谢谢.
好吧,只需快速浏览一下,你就有一个循环while (first != last),然后你不会重新分配其中一个变量.请记住,!=检查引用相等性("这些是完全相同的对象")不是逻辑相等(根据Object.equals(Object)方法).因此,如果first != last进入该循环,您将永远不会退出该循环.
之前在while (index != temp.next)循环中发生了类似的事情.
如果你有一个调试器,我会逐步尝试自己找出无限循环的位置.如果您尚未学习如何使用调试器,那么现在是学习的好时机.如果你还没有时间,你可以回到经过时间考验的技巧,System.out.println("here!")在各个地方打印出调试行().我相信他们中的一个会开始说"这里!这里!这里!这里!" 并准确地告诉你你在无限循环中的位置.
| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |