gpt4 book ai didi

一个小类中的 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 13:16:35 26 4
gpt4 key购买 nike

我的 java 类出现 NullPointerException。请帮忙!错误信息:

java.lang.NullPointerException at
RandomizedQueue.dequeue(52 line) at
RandomizedQueue$IndependantIterator.next (88 line) at
RandomizedQueue.main (104)

我已在错误代码行末尾签署了行号。

import java.util.Iterator;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int number=0;
private Node first=null;
private Node end=null;
private class Node {
Item item;
Node next=null;
Node last=null;
}
private Node Random() {
double r = Math.random();
int n = (int) (r*number);
if(n==0) n=1;
Node ob=first;
for(int i=0;i<(n-1);i++) {
ob = ob.next;
}
return ob;
}

public RandomizedQueue() {
Node empty=new Node();
}
public boolean isEmpty() {
return number==0;
}
public int size() {
return number;
}
public void enqueue(Item item) {
if(item==null) throw new NullPointerException();
number++;
if(first==null) {
first = new Node();
end = first;
first.item = item;
}
else {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
oldfirst.last = first;
}
}
public Item dequeue() {
Node ob=Random();
Item back=ob.item;
if(ob==end) {
end = ob.last;
ob.last.next=null; //52 line
}else if(ob==first) {
first=first.next;
first.last=null;
}
else {
ob.last.next=ob.next;
ob.next.last=ob.last;
}
return back;
}


public Node sample() {
return Random();
}
public Iterator<Item> iterator() {
return new IndepentRandomIterator();
}
private class IndepentRandomIterator implements Iterator<Item> {
private RandomizedQueue<Item> iq = new RandomizedQueue<Item>();
Node scan = first;
public IndepentRandomIterator() {
while(scan != null) {
iq.enqueue(scan.item);
scan=scan.next;
}
}
public boolean hasNext() {
return iq.number >0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if(iq.number==0) throw new java.util.NoSuchElementException();
return iq.dequeue(); //88
}
}
public static void main(String[] args) {
RandomizedQueue<String> test = new RandomizedQueue<String>();
test.enqueue("Luo");
test.enqueue("Jiebin");
test.enqueue("is");
test.enqueue("genious");
test.dequeue();
test.dequeue();
StdOut.println("Is it empty?"+test.isEmpty());
StdOut.println("Size: "+test.size());
StdOut.println("A sample: "+test.sample());
Iterator<String> it = test.iterator();
while(it.hasNext()) {
String s = it.next(); //104
}
}
}

最佳答案

这是因为ob.lastnull。唯一设置结束的时间是当 item 位于 enqueue() 中的第一个时。并且 last 永远不会在那里设置。在 dequeue() 中,如果 ob == end,它将转到 if block 。由于 end.last == null,因此 ob.last == null 也会抛出 NPE。

关于一个小类中的 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22421197/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com