gpt4 book ai didi

java - 列表-RemoveFirst 获取 NullPointerException

转载 作者:太空宇宙 更新时间:2023-11-04 14:51:47 25 4
gpt4 key购买 nike

我正在尝试使用列表执行removeFirst(),删除列表的第一个节点并返回删除的值。

这是我得到的:

    public E removeFirst() {
E value=first.val;

first=first.next;
size--;
return value;
}
public void addLast(E v) {
last = new Node(v,last);
size++;
}

其他类:

class Cliente {
String nome;
int tchegada;
int np;

Cliente(String n, int tc, int p) {
nome = n;
tchegada = tc;
np = p;
}
}

列表:

    class List<E>  {
private int size;
private Node first;
private Node last;

public boolean isEmpty() {return (size == 0);}
public int size() {return size;}

// construtor de lista vazia
List() {
size = 0;
first = last = null;
}

// um no da lista
private class Node {
E val;
Node next;

Node(E v, Node n) {
val = v;
next = n;
}
}
(...)

主要:

    class Prob106_v0 {

public static void main(String args[]) {
Scanner in = new Scanner(System.in);

// Read the flag
int flag = in.nextInt();

// Read the boxes to an array
int n = in.nextInt();
Caixa caixas[] = new Caixa[n];
for (int i=0; i<n; i++) {
int k = in.nextInt();
caixas[i] = new Caixa(k);
}

// Read the clients to a list of objects
int c = in.nextInt();
List<Cliente> clientes= new List<Cliente>();
for (int i=0; i<c; i++) {
String nome = in.next();
int tempo_chegada = in.nextInt();
int num_produtos = in.nextInt();
clientes.addLast(new Cliente(nome, tempo_chegada, num_produtos));
}

// Flag 0 - Remove each client and write the name of the one just removed
if(flag == 0) {
while(!clientes.isEmpty()) {
Cliente cli = clientes.removeFirst();
System.out.println(cli.nome);
}
} else {
// This doesn't matter, it's another part of the program I haven't finished.
Subtarefas.resolve(flag, n, caixas, clientes);
}
}

}

继续,我应该删除列表“clientes”的第一个元素并返回我刚刚删除的内容,在本例中为客户端名称 (cliente.nome),直到没有任何可删除的内容 (null)。

但我收到 NullPointException

    Exception in thread "main" java.lang.NullPointerException
at List.removeFirst(Prob106_v0.java:80)
at Prob106_v0.main(Prob106_v0.java:135)

编辑:当列表为空时,将不会使用RemoveFirst。但我发现当大小为1时,会产生异常。我该如何解决这个问题?

最佳答案

如果您的列表只有一个元素,则此片段:

  public E removeFirst() {
E value=first.val;

first=first.next;
size--;
}

return value;
}

将导致NullPointException

 public E removeFirst() {
E value=first.val;
if (size>=2)
{
first=first.next;
}
else if (size==1)
{
last=null;
}
size--;
return value;
}

关于java - 列表-RemoveFirst 获取 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23679007/

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