2014-03-25 36 views
0

因此,我在数组列表中有几个“学生”对象,每个学生都有一个数组列表。我如何访问特定学生的所有课程?提前致谢。从存储在数组列表中的对象访问数组列表的所有元素(2维)

Scanner studentCourse = new Scanner(System.in); 
int j = 0; 

System.out.println("Which students course(s) do you want to view?"); 
for(Student l:listStudent) { 
    System.out.print(j+1 + ")"); 
    System.out.println(l); 
    j++; 
} 
int course = studentCourse.nextInt(); 

int k = s.listCourse.size();//need this to be the size of the correct array list 
int l = 0; 

while(l < k){ 
    System.out.println(s.listCourse.get(0));//need this to print all of the elements in the correct array list 
} 

break; 

public class Student { 

    String studentFirstName, studentLastName; 
    int studentID; 
    double studentGPA; 
    ArrayList<Course> listCourse = new ArrayList<>(); 

} 

回答

1

你提的问题是非常可以理解的,但不是你的代码。

Student student = studentList.get(indexPosition); 
//ArrayList gives this flexibility and that's the advantage of ArrayList over other Lists 

if(student.getCoursesList()!=null && !student.getCoursesList().isEmpty()){ 
    for(Course course: student.getCoursesList()){ 
     System.out.println(course); 
    } 
} 
+0

是的,我知道,我的代码已经改变了很多次,我都混淆了,并认为我应该至少发布一些东西。当我没有发布代码时,每个人都会被制作哈哈。 –

+0

这是说这行:Student student = studentList.get(indexPosition);出境限制 –

+0

我修正了界限问题,但由于某种原因没有列印出来。它只是继续我所做的主菜单... –

1

看看使用for

for (Course course : s.listCourse) { 
    System.out.println(course); 
} 
1

您可以使用getter & setter方法在Student类或只是使用for循环,如下图所示。

for(Course course : s.listCourse) { 
    System.out.println(course); 
} 
0

你当然可以使用getter。通过使用你可以做到以下几点:

int len = s.listCourse.size(); 
for(int i = 0; i<=len; i++) { 
    System.out.println(s.listCourse.get(i).getCourse()); 
} 
相关问题