ฉันมี ArrayList อยู่ในหลักและฉันมีเรียนกับ constructor ข้างในมันและวิธีการที่จะพิมพ์ข้อมูลออกมา ฉันเพิ่มเป็นคนใหม่วัตถุกับข้อมูลใหม่ตอนที่โทรมาเพิ่มมันไป ArrayList ต้องเก็บมันไว้ในที่นึง สิ่งที่ฉันมีช่วงเวลาที่ยากลำบากมากเป็นรูปแบบการสั่งงานพิมพ์ข้อมูลอยู่ ฉันพยายามมันกับธรรมดาอาเรย์แต่ฉันต้องการที่จะใช้ ArrayList. ฉันต้องการที่จะสามารถไปดัชนีของที่ระบุวัตถุและพิมพ์วัตถุเป็นข้อมูล สำหรับตัวอย่างเช่นรหัสทางด้านล่างสุดท้ายสอนบรรทัด:
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?
}
}
ช่วยหรือช่วยทำให้ชัดเจนคือ greatly นเกียรติอย่างยิ่ง