how do I generate objects with a java loop?

1
public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);
    System.out.println("Introduzca el numero deseado de objetos: ");
    int n = teclado.nextInt();
    String vector[] = new String[n];

    for (int i = 0; i < n; i++) {
        System.out.println("Introduzca el nombre:");
        Familiares vector[i] = new Familiares("paco");
    }
}

I found this but it is still not very clear to me how I generate from a new instance

    
asked by frank copser 28.08.2017 в 07:46
source

4 answers

1

The second line within the code seems incorrect:

public static void main( String[] args ) {
    Scanner teclado = new Scanner(System.in);
    System.out.println( "Introduzca el numero deseado de objetos: " );
    int n = teclado.nextInt();
    String vector[] = new String[n];

    for ( int i = 0; i < n; i++ ) {
        System.out.println( "Introduzca el nombre:" );
        //Familiares vector[i] = new Familiares("paco");
    }
}

You have already declared an array of String objects beforehand, so you should add objects of that type to it, and see what the code is like. , read the data by keyboard. I would replace your loop with this one:

for ( int i = 0; i < n; i++ ) {
    System.out.println( "Introduzca el nombre:" );

    Scanner datoEntrada = new Scanner( System.in );
    vector[i] = (String) datoEntrada.nextLine(); //por ejemplo "Paco"
}

Greetings.

    
answered by 28.08.2017 в 08:58
0

You have a small concept error.

Suppose this is your family class and it goes in another file:

class Familiares {

    private String nombre;

    public Familiares(String nombre) {
        this.nombre = nombre;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    //ESTO ES PARA PODER VER MÁS FACILMENTE LA INFORMACIÓN QUE CONTIENE LA
    // INSTANCIA QUE CREAMOS. CADA INSTANCIA (new Familiar("paco")) TE 
    //   MOSTRARA SU INFO.
    @Override
    public String toString(){

        return "Nombre: "+this.nombre;

    }


}

There are only a few small mistakes

public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);
    System.out.println("Introduzca el numero deseado de objetos: ");
    int n = teclado.nextInt();

    //ESTA LINEA TIENE QUE TENER DECLARADO EL TIPO FAMILIARES.
    // EL VECTOR ESTA CONFORMADO SOLO DE TIPOS FAMILIARES. 
    Familiares vector[] = new Familiares[n];

    for (int i = 0; i < n; i++) {
        System.out.println("Introduzca el nombre:");
        String nombre = teclado.next();
        //NO ES NECESARIO VOLVER A DECLARAR Familiares Vector[] = .... 
        //POR QUE YA LA DECLARASTE Y LE DISTE SU TAMAÑO. 
        //LO QUE SE HACE AQUÍ ES CREAR LA INSTANCIA DE Famliares y guardarla
        // EN vector[i].

        vector[i] = new Familiares(nombre);

        // LA MANERA EN QUE LO TENIAS NO TE FUNCIONABA POR QUE INICIALIZABAS
        // CADA VEZ EL VECTOR PERO NO COMO String, SINO COMO Familiares. 
        // DICHO DE OTRA MANERA. BORRABAS LO ANTERIOR Y PONIAS ALGO NUEVO.

    }


    //ESTA LINEA SOLO ES PARA ITINERAR SOBRE TODOS LOS OBJETOS. 
    System.out.println("El modo que me gusta.");
    for (Familiares familiares : vector) {
        System.out.println(familiares.toString());
    }

    //TAMBIEN PUEDES HACERLO ASÍ, DIRECTAMENTE SOBRE EL VECTOR:
    System.out.println("El modo refinado");
    for (int i = 0; i < vector.length; i++) {
        Familiares familiares = vector[i];
        System.out.println(familiares.toString());
    }

    // O UN POCO MÁS INFORMAL. 
    System.out.println("El clásico");
    for (int i = 0; i < vector.length; i++) {

        System.out.println(vector[i].toString());
    }


}

This way you have each object stored with your information. The nice thing about this is that you can add more parameters to the Familiares class without much fear of creating hard to follow errors.

    
answered by 28.08.2017 в 16:19
0

I recommend using ArrayList to save objects:

public static void main(String[] args) {

 Scanner teclado = new Scanner(System.in);
 System.out.println("Introduzca el numero deseado de objetos: ");
 int n = teclado.nextInt();
 ArrayList<Familiares> familiaresAL = new ArrayList<>();

 for (int i = 0; i < n; i++) {
    System.out.println("Introduzca el nombre:");
    Familiares familiar = new Familiares("paco");
    familiaresAL.add(familiar);     
 }

}
    
answered by 28.08.2017 в 17:39
0

First I'll explain the line where you create an instance of the Familiares class.

Familiares vector[i] = new Familiares("paco");

What that line of code is doing is to create an instance of the Family class, in Familiars there must be a constructor that receives me a string type data because you are sending it "paco", additional when placing that line inside a loop you will create several instances called in the same way and all with the data paco.

Now to store data in an array, you must first create the vector, read the data you need to enter and store the data in the vector, it would be like this:

public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);
    System.out.println("Introduzca el numero deseado de objetos: ");
    int n = teclado.nextInt();
    String nombre;
    String vector[] = new String[n];

    for (int i = 0; i < n; i++) {
        System.out.println("Introduzca el nombre:");
        nombre = teclado.nextLine();
        vector[i] = nombre;
    }
}

What you are doing is creating and reading the variable n int type to define the size of the array, then create the variable name String type to store the name of the data you want in each position of the array, enter the cycle and travel the array starts at 0 and goes up to n, for each position it will read the name and store it in the indicated position of the vector. For example, I entered n = 2, doing a desktop test would look something like this:

public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);
    System.out.println("Introduzca el numero deseado de objetos: ");
    int n = teclado.nextInt(); // n=2

    String nombre;
    String vector[] = new String[2]; // asigna n = 2

    for (int i = 0; i < 2; i++) {
        System.out.println("Introduzca el nombre:");
        nombre = teclado.nextLine(); // i = 0 , nombre =Marcela
        vector[i] = nombre; // vector[0] = Marcela
        //luego al subir al bucle va a aumentar i, sería algo así i = 0 + 1 por 
        //lo tanto i=1 y realiza nuevamente el proceso:
        //nombre = Camilo
        //vector[1] = Camilo;
        //i = 1 + 1 por lo tanto i=2 y al no cumplirse la condición del ciclo 
        // que i < 2, sale del ciclo y termina el programa.
    }
}

I hope I was clear with the information. Greetings.

    
answered by 28.08.2017 в 15:16