如何打印arraylist?-java

rt4zxlrg  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(541)

问题如下。

public class University {
ArrayList<Student> students;

public University() {
    students = new ArrayList<Student>();
}

public void addStudent(Student students) {
    this.students.add(students);
}}
public class Student {
String name;
String studentID;
static int studentNumber = 0;

Student(String name, String sID){
    this.name = name;
    this.studentID = sID;
    studentNumber++;
}}
public class TestUniversity {

public static void main(String[] args) {
    University universityRegister = new University(); 
    Student studentRegister = new Student("Rachel Green", "a1234");
    universityRegister.addStudent(studentRegister);

    studentRegister = new Student("Monica Geller", "a12345");
    universityRegister.addStudent(studentRegister);

    studentRegister = new Student("Ross Geller", "a1111");
    universityRegister.addStudent(studentRegister);

    System.out.println("Number of student in University: " + Student.studentNumber);        
}}

答。我在3个不同的文件中创建了3个类,1.student,2.university,3.universitytester。
b。我创建了3个studnet类型的对象,并将它们作为arraylist存储在university类中。
我想知道如何打印学生名单,包括大学英语班的所有信息?将来,我将创建另一个名为stuff的对象,并将其作为arraylist stufflist存储在university类中。因此,我不想打印班级学生名单。

yb3bgrhw

yb3bgrhw1#

将此添加到学生课堂:

@Override
  public String toString() {
    return String.format("Student: %s , StudentID: %s", name, studentID);
  }

然后你可以像这样打印整个数组:

System.out.println("Students: " universityRegister.students);

//Or like this:

for(Student st: universityRegister.students){
 System.out.println(st);
}
e1xvtsh3

e1xvtsh32#

重写student类中的tostring()方法,如下所示:

import java.util.StringJoiner;

public class Student {
  String name;
  String studentID;
  static int studentNumber = 0;

  Student(String name, String sID) {
    this.name = name;
    this.studentID = sID;
    studentNumber++;
  }

  @Override
  public String toString() {
    return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
        .add("name='" + name + "'")
        .add("studentID='" + studentID + "'")
        .toString();
  }
}

现在您可以在testuniversity中打印数组列表,如下所示:

System.out.println("Student Details: " + universityRegister.students);

相关问题