多态数组Java的问题

时间:2016-08-19 20:52:03

标签: java arrays

这些单元测试仅打印出测试问题的消息。如果您的代码是正确的,单元测试将以静默方式成功,而不会有任何成功消息。我需要在没有任何错误消息的情况下点亮它。我不确定我做错了什么,我是一个相当新的程序员,所以请耐心等待。这是我遇到问题的GetCourseByCourseID方法。除了CourseList之外,我不应该对任何类进行更改。特别是GetCourseByCourseID方法。

class CourseList  
{
public Course[] CourseArray =
{
    new Course ("CIS 400", "OO Analysis & Design", 4, "Important class", "CIS 110") ,
    new Course ("CIS 150A" , "VB.NET Programming", 4, "Good Introduction to programming", "CIS 100") ,
    new Course ("CIS 150B", "C# Programming with labs", 4, "Follow-up to CIS 100", "CIS 100")
};


   public Course GetCourseByCourseID(String id)
   {

     for (Course C : CourseArray)
     {

     }
     return null;
   }
}




class CourseListTest
{
  public static void main(String[] args)
  {
    GetCourseByCourseIDTestWhenCourseExists();
    GetCourseByCourseIDTestWhenCourseDoesNotExist();
  }


public static void GetCourseByCourseIDTestWhenCourseExists()
{

    CourseList myCourseList = new CourseList();
    Course myCourse = myCourseList.GetCourseByCourseID("CIS 400");
    if (myCourse.CourseID != "CIS 400")
        System.out.println("ERROR - GetCourseByCourseIDTestWhenCourseExists(): Returned CourseID Not equal (CIS 400)");
}

public static void GetCourseByCourseIDTestWhenCourseDoesNotExist()
{

    CourseList myCourseList = new CourseList();
    Course myCourse = myCourseList.GetCourseByCourseID("CIS 101");
    if (myCourse != null)
        System.out.println("ERROR - GetCourseByCourseIDTestWhenCourseDoesNotExist(): should have returned null");
}
}



class Course
{
public Course(String id, String title, int creditHours, String description, String prerequisiteCourse)
{
    this.CourseID = id;
    this.CourseTitle = title;
    this.CreditHours = creditHours;
    this.Description = description;
    this.PrerequisiteCourse = prerequisiteCourse;
}


public String CourseID;
public String CourseTitle;
public int CreditHours;
public String Description;
public String PrerequisiteCourse;

1 个答案:

答案 0 :(得分:0)

练习的目的是验证GetCourseByCourseID(String id)方法是否返回与指定课程ID相对应的Course,如果没有退出此类课程则返回null。要实现这一点,您必须循环所有已知课程,并将每个课程的ID与id参数进行比较。如果找到匹配项,则课程将返回给调用者,否则该方法将返回null

public Course GetCourseByCourseID(String id) {

    for (Course C : CourseArray) {
        if (C.CourseID.equals(id)) {
            return course;
        }
    }
    return null;
}

我同意其他海报。从长远来看,编写原始代码的人并没有给你任何好处。它写得很差,绝对不标准。如果你编写这样的代码,你将有很多坏习惯在以后忘掉。