Java.lang.Nullpointerexception because of a list

Asked

Viewed 115 times

1

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

Overview of the system : You want to make a system of bank account registration, and each account has the name of the holder, password, number account and balance. "users" must be able to log in which in name and password already registered, to access functionality of your account. After logging in must be given the deposit, withdrawal and transferring(...)

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

In the Account class a list has been declared to be one of its attributes (I don’t know if it was the right choice, parameterize a list with the class itself in which it is inserted), and its function is to register the accounts in the list inside it with the name of the holder, password, account number and balance. And the Login has the only function to validate a name and password passed, see if in the list have any position that contains that name and password passed and if positive inform which position assigning the number of the correct position to one of its attributes that is called logged in, and then the operation class knows who it can interact with.

The problem is in the validation, the method public void validacao(String nome, int senha) uses a for within it that traverses (or should) the entire list validating the name and password entered with names and passwords already registered, to see if it matches and if it exists. Only when it will do it already running on main gives the error Exception in thread "main" java.lang.NullPointerException as if he were seeking null positions on the list (even "having" several). I believe I rsrs.

I will pass the code of the main until the part that gives the error and the code of the classes Account and Login, Operation does not need because it did not even reach her due to 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();


    }

}

Class counts

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

}
  • The first class is incomplete.

  • I was interested in the problem, could you put the full description of it? Also to help the question.

1 answer

1


Your code has 2 problems.

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

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

In other words, you didn’t create a list of accounts. You just prompted a new account and inserted it into a list within the created object each time the block was called. And then disappears when the loop is finished.

2 - What it looks like is that you would like to use this list within the login object. Only the account was not set to the login object, so it remains null.

Solution

A practical solution that you can implement without changing too much what you have done is as follows:

Classe Conta

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

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

Change the functions below also:

    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 will have to change the other parts like this:

In the while of metodo main:

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

In your Login class change all this:

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

That’s why:

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

What I did above

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

Browser other questions tagged

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