(Java) Come faccio a stampare un oggetto informazioni quando l'oggetto è in un ArrayList? [duplica]

0

Domanda

Ho un ArrayList in principale e ho una classe con un costruttore all'interno di esso e un metodo per stampare i dati. Aggiungere un nuovo oggetto con nuove informazioni, quando chiamato, e aggiunge l'ArrayList di mantenere in un unico luogo. Quello che sto avendo un momento difficile è la sintassi per stampare le informazioni. Ho provato con un normale array, ma ho bisogno di usare ArrayList. Ho bisogno di essere in grado di ottenere l'indice di un oggetto specifico, e la stampa dell'oggetto informazioni. Per esempio, il codice riportato di seguito l'ultimo paio di righe:

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

Qualsiasi aiuto o chiarimento è molto apprezzato.

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

È necessario modificare la definizione di listOfObj da:

ArrayList listOfObj = new ArrayList();

a:

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

La prima volontà di creare un ArrayList di Object gli oggetti di classe.

La seconda per creare un ArrayList di student gli oggetti di classe.

Alcuni ulteriori problemi nel codice:

  1. Dal momento che stai leggendo il nome utilizzando nextLinepotrebbe essere necessario saltare una nuova riga, dopo la lettura, l'anno di nascita come:
...
int birthYear = sc.nextInt();
sc.nextLine();  // Otherwise in the next loop iteration, it will skip reading input and throw some exception
...
  1. Si seleziona un'opzione per gli studenti a visualizzare, ma tale opzione è 1 indicizzati e ArrayList negozi di 0 indicizzati, quindi si dovrebbe modificare la riga sc.nextInt() - 1:
int chosenStudent = sc.nextInt() - 1; // Choose a number that correlates to a student
  1. Scanner può gettare l'eccezione nel caso in cui si entra, per esempio, una stringa invece di un int. Assicurati che la gestione delle eccezioni correttamente utilizzando try-catch i blocchi.
2021-11-24 04:26:42
1
  • Si modifica l'ArrayList defination e aggiungere toString() nella studen classe.
  • E la stampa di tutti gli studenti oggetto al posto di usare per il ciclo di utilizzare solo una sop.

ES:

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

Ciao, puoi modificare la tua risposta e aggiungere un po ' di codice in modo che OP è in grado di capire meglio?
kiner_shah

ok, basta attendere alcune volte
Batek'S

vedere questo codice.
Batek'S
0

Non si può dichiarare il tipo di ArrayList mentre inizializzare listOfObj e names in ArrayList.

Qui è giusto modo per dichiarare ArrayList:

ArrayList<type> list = new ArrayList();

E l'altro problema è che mentre nel recuperare dati da ArrayList. variabile chosenStudent prendere posizione dell'utente e di ottenere i dati da listOfObj ma l'indice è partire da 0 non 1.

Per esempio, il vostro ingresso è 2 quindi, ArrayList ottenere i dati dalla seconda posizione, ma l'indice è partire da 1 mentre i dati di stampa. Devi mettere chosenStudent - 1 per ottenere i dati corretti.

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

Qui in basso è il mio codice:

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

In altre lingue

Questa pagina è in altre lingue

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