在java中使用for each循环打印类成员,其实例存储在class类型的LinkedList中

在java中使用for each循环打印类成员,其实例存储在class类型的LinkedList中,java,foreach,collections,Java,Foreach,Collections,有一个名为Student的类,它包含成员变量Id、fname和lname。我希望遍历存储在链表中的对象,并在将它们添加到列表中的同时打印通过构造函数给出的值 class Coll{ public static void main(String args[])throws Exception{ List<Student> stud = new LinkedList<Student>(); stud.

有一个名为Student的类,它包含成员变量
Id
fname
lname
。我希望遍历存储在链表中的对象,并在将它们添加到列表中的同时打印通过构造函数给出的值

class Coll{
    public static void main(String args[])throws Exception{
        
        List<Student> stud = new LinkedList<Student>();
        
        stud.add(new Student(101, "Sid", "Kulk"));
        stud.add(new Student(102, "avin", "uti"));
        stud.add(new Student(103, "jack", "tak"));
        stud.add(new Student(104, "Tim", "Dou"));
        
        System.out.println("Student ID\tFname\tLname");
        for(Student s:stud){
            System.out.println(s.getId()+"\t"+s.getFname+"\t"+s.getLname);
        }
    }
}
如果类似于“您想在每次拨打电话时打印列表内容stud.add(new Student(…);


然后,您需要一个自定义的链表包装器。

在将值打印到控制台时,您忘记在
getFname
getLname
方法之后添加圆括号。应该是这样的:

System.out.println(s.getId()+"\t"+s.getFname()+"\t"+s.getLname());

如果我没有弄错你的答案。你想在添加到列表时打印新学生,对吗

那么你基本上可以做到这一点

Student(int id, String fname, String lname){
    Id = id;
    this.fname = fname;
    this.lname = lname;
    System.out.println(this.getId()+"\t"+this.getFname() +"\t"+ this.getLname());
}

因为您在添加到列表时创建了学生类。

您忘记添加收到的问题和/或错误消息。我想是他添加的。他想在列表中添加时打印通过构造函数给出的值。实际上,我不想在每次调用构造函数后打印内容,无论如何,谢谢。谢谢!我的坏…-)
Student(int id, String fname, String lname){
    Id = id;
    this.fname = fname;
    this.lname = lname;
    System.out.println(this.getId()+"\t"+this.getFname() +"\t"+ this.getLname());
}