一起打印2个列表

时间:2018-03-19 15:14:24

标签: java list class

我正在尝试使用University类

从Student类打印StudentList

大学课程代码:

public class University {
    Unit[] units = new Unit[3];
    Student student1;
    Student student2;
    Student student3;


public void printStatus() {
    System.out.println("Welcome to Java University");
    System.out.println();
    createUnits();
    displayUnits();
    System.out.println("Thank you for using Java University");
}
public void createUnits() {
    units[0] = new Unit("FIT1234", "Advance Bogosorts");
    student1 = new Student(1234, "Mark", "Stevens");
    student2 = new Student(5678, "Steven", "Perry");
    units[1] = new Unit("FIT2345", "Java Programming");
    student3 = new Student(9012, "Cooper", "Smith");
    units[2] = new Unit("FIT3456"," Java Fundamentals");

}

public void displayUnits() {
    for (int i =0; i<units.length; i++) {
        System.out.println(units[i].description());
    System.out.println(student1.description());
    System.out.println(student2.description());
    System.out.println(student3.description());
        }
    }

}

StudentList代码:

import java.util.ArrayList;
import java.util.List;

public class Unit {
    private String unitcode;
    private String unitname;


public Unit(String x,String y) {
    unitcode = x;
    unitname = y;

}
private final List<Student> studentList = new ArrayList<>();

public boolean addStudents(Student newStudents){
        studentList.add(newStudents);
        return true;

}

public String description() {
        return unitcode + " " + unitname;
        }


}

我得到的输出

    Welcome to Java University
    FIT1234 Advance Bogosorts
    1234 Mark Stevens
    5678 Steven Perry
    9012 Cooper Smith
    FIT2345 Java Programming
    1234 Mark Stevens
    5678 Steven Perry
    9012 Cooper Smith
    FIT3456  Java Fundamentals
    1234 Mark Stevens
    5678 Steven Perry
    9012 Cooper Smith
    Thank you for using Java University

我想要的输出

Welcome to Java University
FIT1234 Advance Bogosorts
1234 Mark Stevens
5678 Steven Perry
FIT2345 Java Programming
9012 Cooper Smith
FIT3456  Java Fundamentals
Thank you for using Java University

我不知道自己做错了什么。我制作了一份学生名单,并将每个学生添加到列表中,但我没有得到正确的输出。我想将学生添加到单元列表中,以便每个学生都注册到一个单元中,或者我是否按错误顺序打印?有人可以给我一个解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以修改方法displayUnits以仅打印在给定课程上注册的学生:

public void displayUnits() {
    for (int i =0; i<units.length; i++) {
        System.out.println(units[i].description());

        for (Student student: units[i].getStudents()) {
            System.out.println(student.description());
        }  
    }
}

要实现这一目标,您需要

1)在课程Unit中添加一个getter方法:

public class Unit {
   ...
   private final List<Student> studentList = new ArrayList<>();

   public List<Student> getStudents() {
      return studentList;
   }
   ...
}

2)填充Unit个对象中的学生列表 - 可能会删除实例变量student1student2和{{1} }:

student3

答案 1 :(得分:0)

单位和学生之间没有联系,所以我认为你需要将学生添加到单位......