java.lang.NullPointerException

-2

Main class presenting problem in call of method createNewContact and insertCustomer:

        case 1:
            cliente = new Cliente();

            cliente.setNome(JOptionPane.showInputDialog("Nome: "));

            cliente.setCpf(Long.parseLong(JOptionPane
                    .showInputDialog("Cpf: ")));

            try {
                cliente.criaNovaConta();

                JOptionPane.showMessageDialog(
                        null,
                        "Nome: " + cliente.getNome() + "\nCpf: "
                                + cliente.getCpf()
                                + "\nNúmero da conta corrente: "
                                + cliente.conta.getNumeroConta());
            } catch (RuntimeException re) {
                System.out.println("Erro ao gerar número de conta: " + re);
            }

            try {
                banco.inserirCliente(cliente);
            } catch (RuntimeException re) {
                System.out.println("Erro ao inserir novo cliente: " + re);
            }

            break;

The methods of my Client class:

 public ContaBancaria conta;

 public Cliente() {
   }

 public void criaNovaConta() {
    conta = new ContaBancaria();
    conta.setNumeroConta();
}

The method of my Bank Account class for the problem:

public void setNumeroConta() {
    boolean achou = false;
    int nConta = aleatorio.nextInt(10000) + 99999;

    for (Cliente c : banco.clientes) {
        if (c.conta.numeroConta == nConta) {
            achou = true;
        }
    }
    if (achou) {
        setNumeroConta();
    } else {
        this.numeroConta = nConta;
    }
}

The method of my Bank class for the problem:

List<Cliente> clientes;

public void inserirCliente(Cliente cliente) {
        clientes.add(cliente);
        JOptionPane.showMessageDialog(null, "Conta cadastrada com sucesso!");
    }
    
asked by anonymous 22.06.2015 / 16:18

2 answers

5

Look at the code below:

cliente = new Cliente();

cliente.setNome(JOptionPane.showInputDialog("Nome: "));

cliente.setCpf(Long.parseLong(JOptionPane
        .showInputDialog("Cpf: ")));

try {
    cliente.conta.setNumeroConta();

Create a client that will initially have the field conta as null . Then you try to access a method of the conta field that is null . The result is NullPointerException .

    
22.06.2015 / 16:35
1

Change the constructor of your Client class to always create a BankAccount instance together.

public class Cliente {

    // seus atributos

    public Cliente() {
        this.conta = new ContaBancaria();
    }

    // Generate Getters e Setters
}

Another suggestion is to change the attribute conta to private and create its respective get / set.

    
22.06.2015 / 17:37