在Arraylist中搜索

时间:2011-01-04 22:51:13

标签: java loops arraylist

目前我有两节课。课堂班和学校班。我想在学校课程public void showClassRoomDetails中编写一个方法,该方法只使用teacherName查找课堂详细信息。

e.g。 teacherName = Daniel className = Science

teacherName = Bob className = Maths

因此,当我输入Bob时,它会打印出Bob和Maths

很多,谢谢

public class Classroom
{
private String classRoomName;
private String teacherName;

public void setClassRoomName(String newClassRoomName)
{
    classRoomName = newClassRoomName;

}

public String returnClassRoomName()
{
    return classRoomName;
}

public void setTeacherName(String newTeacherName)
{
    teacherName = newTeacherName;

}

public String returnTeacherName()
{
    return teacherName;
}
}





import java.util.ArrayList;

public class School
{
private ArrayList<Classroom> classrooms;
private String classRoomName;
private String teacherName;

public School()
{
    classrooms =  new ArrayList<Classroom>();
}

public void addClassRoom(Classroom newClassRoom, String theClassRoomName)
{
    classrooms.add(newClassRoom);
    classRoomName = theClassRoomName;
}

public void addTeacherToClassRoom(int classroomId, String TeacherName)
{
    if (classroomId < classrooms.size() ) {
        classrooms.get(classroomId).setTeacherName(TeacherName);
    }
}

public void showClassRoomDetails
{
    //loop
   System.out.println(returnClassRoomName);
   System.out.println(returnTeacherName);     
}
}

3 个答案:

答案 0 :(得分:1)

你真的需要一份清单吗? 一个地图举办教室 - 教师协会将更有助于你想要实现的目标。 但是代码中也存在一些奇怪的东西:例如,为什么在School类中将classRoomName和teacherName作为实例变量?

答案 1 :(得分:0)

更改方法签名以将targetTeacherName作为参数。穿过教室,直到找到一位老师。输出该教室的信息。

答案 2 :(得分:0)

由于您使用的是ArrayList,因此只需对每个语句使用a:

public void showClassRoomDetails(String teacherName)
{
  for (Classroom classroom : this.classrooms)
  {
    if (classroom.returnTeacherName().equals(teacherName))
    {
      System.out.println(classroom.returnClassRoomName());
      System.out.println(classroom.returnTeacherName());   
      break;
    }
  } 
}

作为一个小建议,不要将方法命名为returnXxx(),而是使用getXxx(),它是标准的Javabean约定。