Find an object inside an ArrayList

2

I created a Conta class and set its attributes. In another part of the code, I have defined values for your attributes and added it to a ArrayList , now I need to select it and start the value of one of its attributes, but I am not able to follow the code:

Account class:

public static class Conta {
    //definindo a classe conta

    int numero;
    String nome_titular;
    double saldo;

    //método para depósito
    void depositar(double valor) {
        this.saldo = this.saldo + valor;
    }

    //método para saque
    boolean sacar(double valor) {
        if (valor > this.saldo) {
            return false;
        } else {
            this.saldo = this.saldo - valor;
            return true;
        }
    }
}

Setting attribute values:

            c.numero = qtdContas;
            System.out.println("Digite o Nome do titular da conta:");
            sc.nextLine();
            c.nome_titular = sc.nextLine();
            System.out.println("Digite o Saldo da conta:");
            c.saldo = sc.nextDouble();
            System.out.println("Conta criada! Numero da conta = " + c.numero);

            Contas.add(c);

Select and start one of your attributes:

            if (Contas.isEmpty() == true) {
                System.out.println("Não há contas cadastradas!");
            } else {
                System.out.println("Digite o número da conta:");
                int nmrConta = sc.nextInt();
                Conta auxiliar = new Conta();
                auxiliar = Contas.get(nmrConta);
                System.out.println(auxiliar.saldo);
            }
    
asked by anonymous 23.03.2017 / 02:12

2 answers

4

The Account class is OK if you remove the static modifier. If you use static you can not use this , because static classes can not be instantiated, that is, they can not have objects created with new .

I've created an executable class with your code with some adaptations to see running. Notice that I kept the essence of the original code. Note: Exceptions if they occur are not being handled.

Follow the code:

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

public class TestConta
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner( System.in );

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

        System.out.print("Digite a quantidade de contas que serão criadas:");
        int qtdContas = sc.nextInt();

            System.out.println("------------------------------");

        for(int i=1; i<=qtdContas; i++)
        {
            Conta c = new Conta();

            //System.out.println("Digite o número da conta:");
            c.numero = i; //sc.nextInt();

            System.out.print("Digite o Nome do titular da conta:");
            c.nome_titular = sc.next();

            System.out.print("Digite o Saldo da conta:");
            c.saldo = sc.nextDouble();


            System.out.println("Conta criada! Numero da conta = " + c.numero);

            contas.add(c);

            System.out.println("------------------------------");
        }


        System.out.println("=========================================================");

        //Verificando as contas criadas

        if (contas.isEmpty() == true) 
        {
            System.out.println("Não há contas cadastradas!");
        } 
        else 
        {
            System.out.print("Digite o número da conta:");
            int nmrConta = sc.nextInt();
            nmrConta--; //pq ao invés de começar o for de zero, começamos de 1, mas guardamos no elemento 0 do array

            Conta auxiliar = contas.get(nmrConta);
            System.out.println("Nome do titular:" + auxiliar.nome_titular);
            System.out.println("Saldo da conta:" +auxiliar.saldo);
        }            
    }

}

Example output generated if data is entered correctly to avoid exceptions:

Digite a quantidade de contas que serão criadas:3
------------------------------
Digite o Nome do titular da conta:Lucas
Digite o Saldo da conta:100
Conta criada! Numero da conta = 1
------------------------------
Digite o Nome do titular da conta:Alexandre
Digite o Saldo da conta:500
Conta criada! Numero da conta = 2
------------------------------
Digite o Nome do titular da conta:Diogo
Digite o Saldo da conta:1000
Conta criada! Numero da conta = 3
------------------------------
=========================================================
Digite o número da conta:2
Nome do titular:Alexandre
Saldo da conta:500.0    

If this answer was helpful in helping to resolve the issue, please accept it as a response and +1 by clicking on the little box above to give me reputation points for the site. If in doubt, ask in the comments.

    
23.03.2017 / 03:13
6

Good to start:

  

All Java API classes, user-defined classes, or classes of any other API - extend the java.lang.Object class, implicitly or explicitly. [ MALA GUPTA, 2015 , p. 51]

Having this in mind, when we think of implementing a java class design

  • Importance of the class Conta method by looking for and removing values from an ArrayList.
  • Importance of equals() method override .

We should be concerned with the following tip:

  

If you are adding instances of a user-defined class as elements to an ArrayList, replace your equals () method or else its equals() or contains() methods may not behave as expected. [ MALA GUPTA, 2015 , p. 281]

To avoid this, it is advisable to overwrite the remove() method, in our case, as follows:

public boolean equals(Object obj) {
    if (obj instanceof Conta) {
       Conta conta = (Conta)obj;
       /** 
        * Considerando apenas o atributo numero para se comparar os objetos.  
        * Alteração do método 'equals()' sugerida pelo @Wryel.
        */
        if (conta.numero == this.numero)
           return true;
    }
    return false;
}

NOTE : Changing method equals() suggested by @Wryel follow the concepts of DDD [ Vaughn Vernon, 2013 ].

For a general approach we have:

  

Methods for overwriting method equals()

     

Method equals() defines an elaborate agreement (set of rules), as follows (directly from the Java API documentation):

     

1. It is reflective - For any non-null reference value x, x.equals (x) should return true. This rule states that an object must be equal to itself, which is reasonable.

     

2. Is symmetric - For any non-null reference values x and y, x.equals (y) should return true if and only if y.equals (x) returns true. This rule states that two objects must be comparable to each other in the same way.

     

3. It is transitive - For any non-null reference values x, y, and z, if x.equals (y) returns true and y.equals (z) returns true, then x.equals (z) should return true. This rule indicates that when comparing objects, you should not selectively compare values based on an object's type.

     

4. Is consistent - For any non-null x and y reference values, the multiple invocations of x.equals (y) consistently return true or consistently return false, as long as no information used in equals comparisons on objects is modified. This rule states that the equals () method must rely on the value of instance variables that can be accessed from memory and should not attempt to rely on values such as the IP address of a system, which can be assigned a separate value after reconnecting to a network.

     

5. - For any non-null reference value x, x.equals (null) should return false. This rule indicates that a nonzero object can never be equal to null.

It's good to also consider:

  

A method that overrides the equals() method does not mean that the compilation failed. [ MALA GUPTA, 2015 , p. 58]

It is relevant to understand that an ArrayList is an object of the List interface, and that in our context the question is used the method equals() marked below:

SOURCE:Figure4.12Listinterfacemethodsgroupedbyfunctionality

04.04.2017 / 19:41