Mam ArrayList w main, i mam klasy z konstruktorem wewnątrz niego i metodą do drukowania danych. Dodaję nowy obiekt z nowych informacji po wywołaniu i dodaję go do listy ArrayList, aby pozostał w jednym miejscu. Co u mnie powoduje trudności, tak, to składnia do drukowania informacji. Próbowałem to z zwykłą tablicą, ale muszę użyć ArrayList. Muszę mieć możliwość uzyskania indeks danego obiektu i wydrukować informacje o tym obiekcie. Na przykład, kod pod ostatnią parę wierszy:
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?
}
}
Będziemy bardzo wdzięczni za każdą pomoc lub wyjaśnienia.