這是我的作業的一部分,因爲我無法弄清楚,我想我會試着在這裏問。實現迭代器出錯並拋出異常
我想在堆棧上使用BST實現迭代器。我編譯並正確運行,結果似乎也是正確的。
但是,當我嘗試使用我學校的自動標記時,它允許我提交代碼,系統將使用其模型進行檢查。我得到了以下錯誤,當涉及到運行的迭代器:
分析中止:您的代碼已經產生了不正確的輸出,未能 拋出一個異常,或拋出一個異常時,它不應該有。
java.lang.Exception的:您的代碼已經產生了不正確的輸出, 未能拋出一個異常,或拋出一個異常時,它 不應該有。在LabProject.main(LabProject.java:115)
我敢肯定,(因爲它說的),我遇到麻煩,在實施某處拋出異常下面,也許我錯過了扔一些觀點。我已經檢查了好幾次,看起來似乎沒有把握好。有人能看到我需要做什麼嗎?
下面是代碼:
public class DictionaryItr<E extends Comparable<E>> implements Iterable<E> {
private MyNode first; // top of stack
public int modCount = 0;
// helper linked list class
private class MyNode {
private E item;
private MyNode next;
}
public DictionaryItr(DictionaryImp.DictNode root) {
first = null;
this.loadNodes(root);
}
@SuppressWarnings("unchecked")
public void loadNodes(DictionaryImp.DictNode node) {
if (node != null) {
loadNodes(node.right);
this.push((E)node.value);
loadNodes(node.left);
}
}
public boolean isEmpty() {
return first == null;
}
public void push(E item) {
MyNode oldfirst = first;
first = new MyNode();
first.item = item;
first.next = oldfirst;
modCount++;
}
public E pop() {
if (isEmpty()) throw new RuntimeException("Stack underflow");
E item = first.item;
first = first.next;
return item;
}
public E peek() {
if (isEmpty()) throw new RuntimeException("Stack underflow");
return first.item;
}
public Iterator<E> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<E> {
private MyNode current = first;
private int expectedModCount;
public ListIterator() {
expectedModCount = modCount;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
current = current.next;
}
public E next() {
if (modCount != expectedModCount) throw new ConcurrentModificationException();
if (!hasNext()) throw new NoSuchElementException("No more elements");
else {
E item = current.item;
current = current.next;
return item;
}
}
}
}
Welp,我非常肯定你的remove()實現應該實際上修改後備集合,而不僅僅是迭代器。 –
嗯,我想它與例外無關,不是嗎?我試圖忽略它的實現,但沒有工作。 – Mountain
你能用迭代器做什麼錯誤?先不用hasNext調用。應該拋出一個異常或返回null? –