(Java) ¿Cómo puedo imprimir un objeto de la información cuando el objeto está en un ArrayList? [duplicar]

0

Pregunta

Tengo un ArrayList en el principal y tengo una clase con un constructor y un método para imprimir los datos. Puedo añadir un objeto nuevo con la nueva información, cuando se le llama, y agrega que el ArrayList para mantenerla en un lugar. Lo que yo estoy teniendo un tiempo difícil es la sintaxis para imprimir la información. He probado con una matriz regular, pero necesito usar ArrayList. Necesito ser capaz de obtener el índice de un objeto específico, y la impresión de que el objeto de la información. Por ejemplo, el código siguiente en el último par de líneas:

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

public class student{

    String name;
    int age;
    int birthYear;

    public student(String name, int age, int birthYear){
        this.name = name;
        this.age = age;
        this.birthYear = birthYear;
    }
    
    public void printStudentInformation(){
        System.out.println(name);
        System.out.println(age);
        System.out.println(birthYear);
    }
}

public class Main{
    public static void main(String[] args){

        ArrayList listOfObj = new ArrayList();
        ArrayList names = new ArrayList();
        Scanner sc = new Scanner(System.in);

        for(int i = 0; i < 3; i++){

            System.out.println("New Student Information:"); // Three student's information will be saved
            String name = sc.nextLine();
            int age = sc.nextInt();
            int birthYear = sc.nextInt();

            student someStudent = new student(name, age, birthYear);
            listOfObj.add(someStudent);
            names.add(name);
        }

        System.out.println("What student's information do you wish to view?");
        for(int i = 0; i < names.size(); i++){
            System.out.println((i + 1) + ") " + names.get(i)); // Prints all students starting from 1
        }
        int chosenStudent = sc.nextInt(); // Choose a number that correlates to a student
        
        // Should print out chosen student's object information
        listOfObj.get(chosenStudent).printStudentInformation(); // This is incorrect, but I would think the syntax would be similar?
        
    }
}

Cualquier ayuda o aclaración es muy apreciado.

arraylist java printing
2021-11-24 04:07:52
3
1

Usted necesita cambiar su definición de listOfObj de:

ArrayList listOfObj = new ArrayList();

a:

ArrayList<student> listOfObj = new ArrayList<>();

El primero será crear un ArrayList de Object los objetos de la clase.

La segunda, crear un ArrayList de student los objetos de la clase.

Cuantos más problemas en su código:

  1. Ya que usted está leyendo el nombre de usar nextLine, usted puede necesitar para saltar de una nueva línea después de leer el año de nacimiento como:
...
int birthYear = sc.nextInt();
sc.nextLine();  // Otherwise in the next loop iteration, it will skip reading input and throw some exception
...
  1. Selecciona una opción para que el estudiante de la pantalla, pero esa opción 1 indexados y ArrayList tiendas de 0 indexados, por lo que se debe cambiar la línea a sc.nextInt() - 1:
int chosenStudent = sc.nextInt() - 1; // Choose a number that correlates to a student
  1. Scanner puede lanzar una excepción en caso de que usted introduzca, por ejemplo, una cadena en lugar de un int. Así que asegúrese de que está correctamente con el tratamiento de excepciones try-catch los bloques.
2021-11-24 04:26:42
1
  • Cambiar el ArrayList defination y agregar toString() en su studen clase.
  • Y para imprimir todos los estudiantes de objeto en lugar de utilizar para el bucle de uso justo uno de los sop.

EX:-

import java.util.*;

class Student {
    private String name;
    private int age;
    private int birthYear;

    public Student() {
        super();
    }

    public Student(String name, int age, int birthYear) {
        super();
        this.name = name;
        this.age = age;
        this.birthYear = birthYear;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getBirthYear() {
        return birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", birthYear=" + birthYear + ", name=" + name + "]";
    }

}

public class DemoArrayList {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<Student>();

        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        for (int i = 0; i < n; i++) {
            scan.nextLine();
            String name = scan.nextLine();
            int age = scan.nextInt();
            int birthYear = scan.nextInt();
            list.add(new Student(name, age, birthYear));
        }

        System.out.println(list);
    }
}

O/P:-

2
joy 
10
2003
jay
20
2005
[Student [age=10, birthYear=2003, name=joy], Student [age=20, birthYear=2005, name=jay]]
2021-11-24 04:14:02

Hola, puedes editar tu respuesta y añadir un poco de código, así por lo que el OP puede entender mejor?
kiner_shah

aceptar sólo tiene que esperar algunas veces
Batek'S

ver ahora este código.
Batek'S
0

Usted no puede declarar el tipo de ArrayList mientras inicializar listOfObj y names en ArrayList.

Aquí es la forma correcta de declarar ArrayList:

ArrayList<type> list = new ArrayList();

Y otro problema es que cuando tienes que obtener los datos de ArrayList. variable chosenStudent tomar la posición del usuario y obtener datos de listOfObj pero el índice es el inicio de 0 no 1.

Por ejemplo, su entrada es 2 entonces, ArrayList obtener datos a partir de la segunda posición, pero su índice de inicio de 1 mientras que los datos de impresión. Usted tiene que poner chosenStudent - 1 para obtener los datos correctos.

listOfObj.get(chosenStudent - 1).printStudentInformation() // chosenStudent = 2 - 1 = 1 

Aquí abajo es mi código:

ArrayList<student> listOfObj = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
Scanner sc = new Scanner(System.in);
    for(int i = 0; i < 3; i++){
        System.out.println("New Student Information:");
        String name = sc.next();
        int age = sc.nextInt();
        int birthYear = sc.nextInt();

        student someStudent = new student(name, age, birthYear);
        listOfObj.add(someStudent);
        names.add(name);
     }

     System.out.println("What student's information do you wish to view?");
     for(int i = 0; i < names.size(); i++){
        System.out.println((i + 1) + ") " + names.get(i));
     }
     int chosenStudent = sc.nextInt();
        
     listOfObj.get(chosenStudent - 1).printStudentInformation();
2021-11-24 04:41:01

En otros idiomas

Esta página está en otros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Slovenský
..................................................................................................................