Erro: "Exception in thread "main" java.lang.NullPointerException"

4 respostas Resolvido
java
Breno_Luizetto

estou tendo este erro: Exception in thread “main” java.lang.NullPointerException
segue as 3 classes utilizadas:
/*public class Fila {

private No first;
private No last;
private int size;

public Fila(){
    first = null;
    last = null;
    size = 0;

}

public boolean isEmpty(){
    return first == null;
}

public void add(String name, int idade){
    No newNode = new No(name, idade);

    No aux = first;
    if(isEmpty()){
        first = newNode;
        last = newNode;
    }if(first.getPreferencia() < newNode.getPreferencia()){
        first = newNode;
        first.setNext(aux);
    }else{
        while(aux.getNext() != null && (aux.getNext().getPreferencia() >= newNode.getPreferencia())){
            aux = aux.getNext();
        }
        newNode.setNext(aux.getNext());
        aux.setNext(newNode);

    }
    size++;
}
public No remove(){
    if(isEmpty()){
        return null;
    }
    No aux = first;

    first = first.getNext();
    if(first == null){
        last = null;
    }
    size --;
    return aux;
}

public String show(){
    String out = "";

    No aux = first;

    while(aux != null){
        out += aux.getName() + aux.getPreferencia() + "-";
        aux = aux.getNext();
    }
    return out;
}

public int size(){
    return size;
}

}
*/public class No {

private String name;
private int preferencial;
private No next;

public No(String name, int preferencial){
    this.name = name;
    this.preferencial = preferencial;
    next = null;

}

public String getName(){
    return name;
}

public void setName(String name){
    this.name = name;
}


public int getPreferencia(){
    return preferencial;
}
public No getNext(){
    return next;

}
public void setNext(No next){
    this.next = next;
}
}

*/

public class Main {
public static void main(String[] args) {

 Fila fila = new Fila();

    fila.add("Huguinho",0);
    fila.add("Zezinho",1);
    fila.add("Luizinho",1);

    System.out.println(fila.show());
   

}

}
*/

4 Respostas

staroski

Posta o StackTrace completo.

J

Geralmente é porque vc usa um método ou algum recurso de uma variável de referência com valor não instanciado, desse modo o objeto tem valor null.
É como tentar fazer isso:
null.metodo();

Portanto, não tem referência à um objeto retornando essa Exception

Breno_Luizetto
Solucao aceita
consegui resolve

o problema estava aqui:

/*

if(isEmpty()){

first = newNode;

last = newNode;

}if(first.getPreferencia() < newNode.getPreferencia()){

first = newNode;

first.setNext(aux);

<em>/

arrumei e deixei assim:

/</em>

if(isEmpty()){
first = newNode;

        last = newNode;

    }else{

        if(first.getPreferencia() < newNode.getPreferencia()){

        first = newNode;

        first.setNext(aux);

*/

J

Por causa do Else :smile:
Q bom q resolveu

Criado 5 de junho de 2020
Ultima resposta 5 de jun. de 2020
Respostas 4
Participantes 3