java.lang.Nullpointerexception

Asked

Viewed 183 times

-2

Main class presenting problem in the call of the method createNew:

        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();
}

My Bank Account class method related to 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 concerning the problem:

List<Cliente> clientes;

public void inserirCliente(Cliente cliente) {
        clientes.add(cliente);
        JOptionPane.showMessageDialog(null, "Conta cadastrada com sucesso!");
    }

2 answers

5

Note the code below:

cliente = new Cliente();

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

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

try {
    cliente.conta.setNumeroConta();

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

1

Change the constructor of your class Client to always create an instance of Bookkeeping along.

public class Cliente {

    // seus atributos

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

    // Generate Getters e Setters
}

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

Browser other questions tagged

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