Use ArrayList to save data of different value

1

I'm trying to save different types of data in an arraylist, mainly String and int to have a database of people. After looking for ways to do it, I decided to create a separate class.

class Persona 
{
    private String nombre;
    private int hora;
    private int dia;
    private int glucosa;
    public Persona(int dia, int hora, int glucosa, String nombre)
    {
        this.nombre = nombre;
        this.hora = hora;
        this.dia = dia;
        this.glucosa= glucosa;
    }

...
}    

And the class that used this data

import java.util.ArrayList;
public class Organizador
{
    private ArrayList<Persona> personas;

    public Organizador()
    {
        ArrayList<Persona> personas = new ArrayList<Persona>();
    }

    public void nuevaPersona()
    {

        personas.add(new Persona(dia, hora, glucosa, nombre));
    }
}

However, it does not let me compile the Organizer class since it does not find the values of day, time, etc. and I am not sure what the problem is and that I am placing it wrong, I am lost.

    
asked by Eleber 04.05.2018 в 15:39
source

3 answers

2

Your application can not invent data! You have this method:

public void nuevaPersona() {

    personas.add(new Persona(dia, hora, glucosa, nombre));
}

Where you are passing 4 parameters to the constructor. But those parameters are neither local variables, nor parameters of the method, nor attributes of class Organizador ... they are not declared anywhere.

You could do something like:

public void nuevaPersona(int dia, int hora, int glucosa, String nombre) {

    personas.add(new Persona(dia, hora, glucosa, nombre));
}

To be able to call this method with the necessary values, for example:

miOrganizador.nuevaPersona(5, 14, 55, "Juan");
    
answered by 04.05.2018 / 15:46
source
0

You must modify the nuevaPersona() method to something like this:

public void nuevaPersona(int dias, int hora, int glucosa, String nombre)
{

    personas.add(new Persona(dia, hora, glucosa, nombre));
}  

That way you can build a person by passing on that data as a parameter and add it to your ArrayList.
The way you were doing it, you were not specifying the data types of the Person object, as stated in the constructor of the class Persona

    
answered by 04.05.2018 в 15:48
0

You have to declare the parameters in the new functionPerson () in Orgnizer as you do it in the Persona constructor:

nuevaPersona(int dia, int hora, int glucosa, String nombre){
  personas.add(new Persona(dia, hora, glucosa, nombre));
}

The other thing is that you can pass a person type in newPersona ():

nuevaPersona(Persona persona){
  personas.add(persona);
}

Although surely the first option is the one you are needing.

    
answered by 04.05.2018 в 15:49