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.