J'ai une liste de tableaux en principal et j'ai une classe avec un constructeur à l'intérieur et une méthode pour imprimer les données. - Je ajouter un nouvel objet avec de nouvelles informations, lorsqu'on l'appelle, et l'ajoute à la liste de tableaux pour le garder en un seul endroit. Ce que je vais avoir un moment difficile est la syntaxe pour imprimer les informations. Je l'ai essayé avec un tableau normal, mais j'ai besoin d'utiliser ArrayList. J'ai besoin d'être en mesure d'obtenir l'index d'un objet spécifique, et de l'impression que l'objet de l'information. Par exemple, le code ci-dessous les deux dernières lignes:
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?
}
}
De l'aide ou des précisions sont grandement appréciés.