Olá,
O seguinte exercício consiste em fazer uma espécie de agenda com um array de objetos.
O código está gerando uma exceção NullPointerException no IF que verifica se a pessoa que está sendo incluída no array já existe.
public class TestaAgenda {
public static void main(String[] args) {
Agenda novaAgenda = new Agenda(5);
boolean foiIncluso;
for(int x = 0;x <= 10;x++){
Pessoa novaPessoa = new Pessoa();
novaPessoa.setNome(JOptionPane.showInputDialog(null,"Nome"));
foiIncluso = novaAgenda.incluiPessoa(novaPessoa);
}
}
A Class acima chama o seguinte método da Class Agenda:
public boolean incluiPessoa(Pessoa novaPessoa) {
int capacidadeAntiga = 0;
boolean foiIncluso = false;
//Se a agenda já contém registros
if(quant > 0){
//Verifica se a pessoa já existe
for(int x = 0;x <= this.agenda.length;x++){
if(novaPessoa.getNome().equals(this.agenda[x].getNome())){
foiIncluso = false;
return foiIncluso;
}
}
//Se a agenda não tiver mais posições disponíveis
if(agenda.length < (quant + 1)){
capacidadeAntiga = this.agenda.length;
Pessoa agendaTemp[] = new Pessoa[this.agenda.length];
//Copia agenda para lista temporária
for(int x = 0;x < this.agenda.length;x++){
agendaTemp[x] = this.agenda[x];
}
//Instância novamente a agenda com 10 posições a mais
this.agenda = new Pessoa[capacidadeAntiga+10];
//Copia lista temporária para agenda nova
for(int x = 0;x < capacidadeAntiga;x++){
this.agenda[x] = agendaTemp[x];
}
}
//Adiciona novo registro na agenda: umaP
this.agenda[quant] = novaPessoa;
quant++;
foiIncluso = true;
}
else{
this.agenda[0] = novaPessoa;
quant++;
foiIncluso = true;
}
return foiIncluso;
}
}
Comentando o IF que verifica se a pessoa já existe o código funciona.
Mas realmente não sei o porque da exceção.
Valeu!