开发者

Searching in an Arraylist

Currently I have two classes. A Classroom class and a School class. I would like to write a method in the School class public void showClassRoomDetails which would find the classroom details by only using the teacherName.

e.g. teacherName = Daniel className = Science

teacherName = Bob className = Maths

so when I input Bob, it would print out Bob and Maths

many, thanks

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 = t开发者_运维百科heClassRoomName;
}

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);     
}
}


Do you really need a list here ? A Map holding classroom - teacher associations would be more helpful for what you're trying to achieve. But there are also strange things in your code: for instance, why do you hold a classRoomName and teacherName as instance variables in your School class ?


Change your method signature to take a targetTeacherName as a parameter. Loop through the classrooms until you find one with that teacher. Output the information of that classroom.


Since you are using an ArrayList you could simply use a for each statement:

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;
    }
  } 
}

As a small suggestion, do not name your methods returnXxx(), use getXxx() instead, it is the standard Javabean convention.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜