Java.lang.NullPointerException because of a list

2

Well, I'm studying java and I was seeing composition, so I decided to do some things:

  

System overview : You want to make a bank account registration system, and each account has a holder name, password, number   of account and balance. "Users" must be able to log in   in the name and password already registered, to access features of your   account. After the log-in must be given the operations of deposit, withdrawal and   transfer (...)

     

This program contains three classes, Account, Login and Operation. Account is   and the basis of the program, Login is an Account and   Operation is a Login and Account association.

In the class Account was declared a list as one of its attributes (I do not know if it was the correct choice, parameterize a list with the class itself is inserted), and the function is to register the accounts in the list that is inside it with holder name, password, account number and balance. And the login has the sole function of validating a last name and password, see if there is any position in the list that contains this last name and password, and if it is positive, inform the position by assigning the correct position number to one of its attributes. calls logged, then the operation class knows who it can interact with.

The problem is in validation, the public void validacao(String nome, int senha) method uses a for inside it that runs (or should) the whole list validating the name and password entered with names and passwords already registered, to see if it hits and if there is . But when it does this by running on main it gives the error Exception in thread "main" java.lang.NullPointerException as if it were looking for null positions in the list (even "having" several). I believe I am.

I'm going to pass the main code to the part that gives the error and the code of the classes Account and Login, Operation does not need because he did not even come to it because of this problem.

   package application1;

import java.util.Locale;
import java.util.Scanner;

import entities1.Conta;
import entities1.Login;
import entities1.Operacao;

public class ProgramContaBancaria {

    public static void main(String[] args) {

        Locale.setDefault(Locale.US);
        Scanner sc = new Scanner(System.in);

        System.out.println("Por favor, faça o cadastro:");

        boolean check = false;
        while(check == false) {
            System.out.println("Digite o nome da conta para cadastro: ");
            String nome = sc.next();

            System.out.println("Digite a senha da conta para cadastro: ");
            int senha = sc.nextInt();

            System.out.println("Digite o número da conta para cadastro: ");
            int numeroDaConta = sc.nextInt();

            System.out.println("Digite o saldo inicial da conta para cadastro: ");
            double saldo = sc.nextDouble();

            Conta conta = new Conta(nome, senha, numeroDaConta, saldo);
            conta.addConta(conta);

            System.out.println();
            System.out.println("Deseja cadastrar mais alguma conta ? (yes/no): ");
            String resposta = sc.next();

            if(resposta.equals("yes")) {
                check = false;
            }
            else if (resposta.equals("no")) {
                check = true;
            }   
        }

        System.out.println("Conta(s) cadastradas com sucesso!");
        System.out.println();
        System.out.println("Entre com nome e senha para efetuar o login: ");
        System.out.print("Nome: ");
        String nome = sc.next();
        System.out.println("Senha: ");
        int senha = sc.nextInt();

        Login login = new Login();
        login.validacao(nome, senha);

        System.out.println("Bem-Vindo "+login.getNome()+", o que deseja fazer ?");
        System.out.println("Depósito $ (digite 1)");
        System.out.println("Saque $ (digite 2)");
        System.out.println("Transferência $ (digite 3)");
        int escolha = sc.nextInt();

        Operacao operacao = new Operacao();
        switch (escolha) {
        case 1:
            System.out.println("Quanto quer depositar ?");
            double valorDeposito = sc.nextDouble();
            operacao.deposito(valorDeposito);
            break;
        case 2:
            System.out.println("Quanto quer sacar ?");
            double valorSaque = sc.nextDouble();
            operacao.saque(valorSaque);
            break;
        case 3:
            System.out.println("Informe o valor da transferência e a conta para qual quer transferir");
            System.out.print("Valor: ");
            double valorTransferencia = sc.nextDouble();
            System.out.print("Conta: ");
            int numeroDaContaTransferir = sc.nextInt();
            operacao.transferencia(valorTransferencia, numeroDaContaTransferir);
            break;
        }
        sc.close();


    }

}

Account Class

package entities1;

import java.util.ArrayList;
import java.util.List;

public class Conta {

    private String nome;
    private Integer senha;
    private Integer numeroDaConta;
    private Double saldo;

    private List<Conta> contas = new ArrayList<>();

    public Conta() {

    }

    public Conta(String nome, Integer senha, Integer numeroDaConta, Double saldo) {     
        this.nome = nome;
        this.senha = senha;
        this.numeroDaConta = numeroDaConta;
        this.saldo = saldo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Integer getSenha() {
        return senha;
    }

    public void setSenha(Integer senha) {
        this.senha = senha;
    }

    public Integer getNumeroDaConta() {
        return numeroDaConta;
    }

    public void setNumeroDaConta(Integer numeroDaConta) {
        this.numeroDaConta = numeroDaConta;
    }

    public Double getSaldo() {
        return saldo;
    }

    public void setSaldo(Double saldo) {
        this.saldo += saldo;
    }

    public void setSaldo1(Double saldo) {
        this.saldo -= saldo;
    }

    public List<Conta> getContas() {
        return contas;
    }

    public void addConta(Conta conta) {
        contas.add(conta);
    }

    public void removeConta(Conta conta) {
        contas.remove(conta);
    }



}

Login class

package entities1;

public class Login {

    private String nome;
    private Integer senha;
    private Integer logado;

    private Conta conta;


    public Login() {
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Integer getSenha() {
        return senha;
    }

    public Integer getLogado() {
        return logado;
    }

    public Conta getConta() {
        return conta;
    }

    public void validacao(String nome, int senha) {
        for (int i = 0; i < conta.getContas().size(); i++) {
            if (conta.getContas().get(i).getNome().equals(nome) && conta.getContas().get(i).getSenha().equals(senha)) {
                logado += i;
                this.nome = nome;
                this.senha = senha;
            }
        }
    }

}
    
asked by anonymous 05.01.2019 / 01:23

2 answers

1

Your code has 2 problems.

1 - You create a new Account object within a while loop that is never used.

while(check == false) {
...
Conta conta = new Conta(nome, senha, numeroDaConta, saldo);
conta.addConta(conta);

That is, you did not create an account list. You just instantiated a new account and inserted it into a list within the created object each time the block was called. And then it disappears when the loop is terminated.

2 - What it looks like is that you would like to use this list inside the login object. However, the account has not been set to the login object, so it remains null.

Solution

A practical solution that you can implement without much change is what you did:

Account Class

Change the attribute of the list of Accounts to static like this:

private static List<Conta> contas = new ArrayList<>();

Change the functions below too:

    public static List<Conta> getContas() {
        return contas;
    }

    public static void addConta(Conta conta) {
        contas.add(conta);
    }

    public static void removeConta(Conta conta) {
        contas.remove(conta);
    }

Now, to use, you'll have to change the other parts like this:

No while of method main:

        Conta conta = new Conta(nome, senha, numeroDaConta, saldo);
        Conta.addConta(conta); // <-- aqui com letra maiuscula

In your class Login change all this:

conta.getContas() // <-- letra minuscula

So:

Conta.getContas() // <-- letra maiuscula

What I did above

I changed all methods and attributes that depended on instances (Objects) for methods and static attributes. So, they belong to the Class and not to the Object, so you do not have to set them in each instance.

    
05.01.2019 / 03:24
0

I think the error is being caused exactly because conta has no value. You only created it, but did not assign any value, such as nome , senha and logado . However, the nome variable can get an SE value, and only SE, the setNome method is used.

So, I think at some point you will have to assign a Conta object to the conta variable, so that you can only use the getContas method. I would advise you to do this in the method constructor , that is, within the Login method. And instead of having to pass the arguments / parameters in the validacao method, you use the information already stored, later overwriting it.

I hope I have helped!

    
05.01.2019 / 03:20