Exception in thread "main" java.lang.Nullpointerexception

Asked

Viewed 2,188 times

0

How do I fix this mistake?

Java - Exception in thread "main" java.lang.Nullpointerexception at Client.Customer Registration(Client.java:43) at Operations.main(Operations.java:9)

Follows 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 everything is OK, but when I try to run with the method main makes the mistake.

Here is the main:

import javax.swing.JOptionPane; 

public class Operacoes { 

    public static void main(String[] args) { 

        Cliente teste1 = new Cliente(); 
        teste1.CadastroCliente(1); 
    } 
}
  • 1

    Igor, welcome to Stackoverflow. Take into account, in future posts, the issue I made in your question.

  • And when you enter a line number of an error, enter the line of this number, it is not easy to identify when put somewhere.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

4

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

This code is very confusing, you are mixing GUI with data.

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

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

I put in the Github for future reference.

It’s still not a good solution but it solves your problem. You put a array of a class within this very class is very odd. Sooner or later you will have other bad consequences.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.