如何从ArrayList中打印某个变量

时间:2016-01-10 23:05:54

标签: java arraylist

如果我使用了错误的术语,我很抱歉,但我只是尝试从ArrayList打印学生的姓名。名称可以在引号中找到。

import java.util.ArrayList;
import java.util.Arrays;


public class Student {
private String name;
private int idNum;

public Student(String string, int i) {
    name = string;
    idNum = i;
}
public String getName()
{return name;}
public int getNum()
{return idNum;}
public String toString()
{return name+" "+idNum;}

public static void main(String[] args) {
    ArrayList<Student> classroom = new ArrayList<Student>();
    Student s1 = new Student("Eugene", 2596);
    classroom.add(0, s1); 
    Student s2 = new Student("Bob", 1111);
    classroom.add(1, s2);
    Student s3 = new Student("Gary", 7993);
    classroom.add(2, s3);
    Student s4 = new Student("Dan", 6689);
    classroom.add(3, s4);
    Student s5 = new Student("Joe Kid", 3592);
    classroom.set(2, s5);
    Student s6 = new Student("Sue Kim", 8541);
    classroom.set(3, s6);
    classroom.remove(0);
    Student s7 = new Student("Bob Lee", 6317);
    classroom.add(s7);
    classroom.remove(4);
    System.out.println(classroom.toString());
    for(int i=0; i<classroom.size(); i++){
        System.out.println(classroom.**getName**(i));
    }
}

}

最后有一个错误的getName(我把它放在星号),我不知道如何解决它。谢谢你,如果你能找到解决方法。

2 个答案:

答案 0 :(得分:2)

你可以做到

for (Student student: classroom) {
    System.out.println(student.getName());
}

答案 1 :(得分:1)

使用此:

System.out.println(classroom.get(i).getName());

您需要先使用Student访问classroom.get(i)对象,然后访问他的name

P.S :如果你正在使用 Java 8 ,你可以这样做:

classroom.stream()
         .forEach(student -> System.out.println(student.getName()));