Exception in thread "main" java.lang.NullPointerException

0

How do I resolve this error?

  

Java - Exception in thread "main" java.lang.NullPointerException at Client.ClientClient (Client.java:43) at Operacoes.main (Operations.java:9)

Follow my code:

import javax.swing.JOptionPane; 

public class Cliente { 

    private String nome; 
    private String telefone; 
    private int codigo; 
    private String rua; 

    void setRua(String z) { 
        rua = z; 
    } 
    void setTelefone(String t) { 
       telefone = t; 
    } 
    void setCodigo(int n) { 
        codigo = n; 
    } 
    void setNome(String name) { 
        nome = name; 
    }

    Cliente cliente[] = new Cliente[30]; 

    void CadastroCliente(int n) { 

        cliente[n].setCodigo(n); 
        cliente[n].setNome(JOptionPane.showInputDialog("Nome: ")); 
        Endereco endereco = new Endereco(); 
        endereco.setLogradouro(JOptionPane.showInputDialog("Logradouro: ")); 
        endereco.setNumero(Integer.parseInt(JOptionPane.showInputDialog("Nº: "))); 
        endereco.setComplemento(JOptionPane.showInputDialog("Complemento: ")); 
        endereco.setCidade(JOptionPane.showInputDialog("Cidade: ")); 
        endereco.setEstado(JOptionPane.showInputDialog("Estado: ")); 
        endereco.setCep(JOptionPane.showInputDialog("CEP: ")); 
        cliente[n].setRua(rua); 

    } 
} 

My Java compiler says that everything is OK, but when I try to run with the main method it gives the error.

Here is main :

import javax.swing.JOptionPane; 

public class Operacoes { 

    public static void main(String[] args) { 

        Cliente teste1 = new Cliente(); 
        teste1.CadastroCliente(1); 
    } 
}
    
asked by anonymous 01.02.2015 / 16:40

1 answer

3

The fact that a compile program does not mean that it is right.

This code is pretty confusing, you're mixing GUI with data.

You need to initialize vector elements before using them. You are trying to write data to a null state. I would have to change the code to something like this:

void CadastroCliente(int n) {
    cliente[n] = new Cliente();
    cliente[n].setCodigo(n); 
    ...

Still not a good solution but solves your problem. You put an array of a class inside this class itself is very odd. Sooner or later you will have other bad consequences.

    
01.02.2015 / 17:07