1 2 Previous Next 19 Replies Latest reply: Feb 11, 2007 1:05 PM by 807606 RSS

    Searching an ArrayList of Student objects using a passed String?

    807606
      I am having trouble searching through an ArrayList of Student objects using only a passed String. I have directions to read in a String value containing a key-value identifying a Student, and then finding the object-reference that matches that key-value in the students ArrayList. My directions say that I need the ability to search this list of objects, given a string. There are several ways to do this, supposedly. I was told that using an ArrayList, you can create a temp-object (of the same class) with the right key-value, and then use the indexOf() method in combination with get(). How do you do this?

      For example, I will input to the program:
      add Bob cs101

      My Student constructor looks like:
      // Student(): specific constructor
           public Student(String nameOfStudent, double gradePointAverage) {
                name = nameOfStudent;
                
                setGPA(gradePointAverage);
                
                courses = new ArrayList();
           }

      So I am supposed to use "Bob" from my input and be able to search through my students ArrayList in order to find the object referenced by "Bob". Can you please help me with this? I know this may be vague, so if you need any more information, please let me know. Thank you very much!
        • 1. Re: Searching an ArrayList of Student objects using a passed String?
          807606
          As per the requirement specified by you, I can understand that the best Data Structure to achieve this is using a Map.

          A Map stores a key/value pair, in which you can specify the Key as the student name and the Value would be the Student object for the corresponding student name that has been stored in the Key.

          The indexOf() method of ArrayList gets you the index of the Student object passed as its parameter. It again is your job to check whether the Student object at that index matches the name you require to find.

          All in all, a Map is a better bet for such a scenario.
          • 2. Re: Searching an ArrayList of Student objects using a passed String?
            796254
            I'd recommend something like this:

            package cruft;

            import java.util.Date;
            import java.util.List;
            import java.util.Arrays;
            import java.text.DateFormat;
            import java.text.SimpleDateFormat;
            import java.text.ParseException;

            /**
            * Date: Feb 11, 2007
            * Time: 1:46:08 PM
            */
            public class StudentSearchDemo
            {
            private List<Student> students;

            public static void main(String[] args)
            {
            StudentSearchDemo searchDemo = new StudentSearchDemo();

            for (int i = 0; i < args.length; ++i)
            {
            Student found = searchDemo.find(args);
            if (found != null)
            {
            System.out.println(found);
            }
            else
            {
            System.out.println("no student found with name " + args[i]);
            }
            }
            }


            public StudentSearchDemo()
            {
            try
            {
            students = Arrays.asList(new Student []
            {
            new Student("foo", Student.DATE_FORMATTER.parse("1-Jan-1980")),
            new Student("bar", Student.DATE_FORMATTER.parse("1-Feb-1980")),
            new Student("baz", Student.DATE_FORMATTER.parse("1-Mar-1980")),
            });
            }
            catch (ParseException e)
            {
            e.printStackTrace();
            }
            }

            public Student find(String name)
            {
            Student found = null;

            for (Student student : students)
            {
            if (student.getName().equals(name))
            {
            found = student;
            break;
            }
            }

            return found;
            }
            }

            class Student
            {
            public static final DateFormat DATE_FORMATTER = new SimpleDateFormat("dd-MMM-yyyy");

            private String name;
            private Date birthDate;

            public Student(String name, Date birthDate)
            {
            if ((name == null) || ("".equals(name.trim())))
            throw new IllegalArgumentException("name cannot be blank or null");

            if (birthDate == null)
            throw new IllegalArgumentException("birth date cannot be null");

            this.name = name;
            this.birthDate = new Date(birthDate.getTime());
            }

            public String getName()
            {
            return name;
            }

            public Date getBirthDate()
            {
            return birthDate;
            }


            public String toString()
            {
            return "Student{" +
            "name='" + name + '\'' +
            ", birthDate=" + DATE_FORMATTER.format(birthDate) +
            '}';
            }
            }
            • 3. Re: Searching an ArrayList of Student objects using a passed String?
              796254
              Screwed up with code tags again:
              package cruft;
              
              import java.util.Date;
              import java.util.List;
              import java.util.Arrays;
              import java.text.DateFormat;
              import java.text.SimpleDateFormat;
              import java.text.ParseException;
              
              /**
               * Date: Feb 11, 2007
               * Time: 1:46:08 PM
               */
              public class StudentSearchDemo
              {
                 private List<Student> students;
              
                 public static void main(String[] args)
                 {
                    StudentSearchDemo searchDemo = new StudentSearchDemo();
              
                    for (int i = 0; i < args.length; ++i)
                    {
                       Student found = searchDemo.find(args);
              if (found != null)
              {
              System.out.println(found);
              }
              else
              {
              System.out.println("no student found with name " + args[i]);
              }
              }
              }


              public StudentSearchDemo()
              {
              try
              {
              students = Arrays.asList(new Student []
              {
              new Student("foo", Student.DATE_FORMATTER.parse("1-Jan-1980")),
              new Student("bar", Student.DATE_FORMATTER.parse("1-Feb-1980")),
              new Student("baz", Student.DATE_FORMATTER.parse("1-Mar-1980")),
              });
              }
              catch (ParseException e)
              {
              e.printStackTrace();
              }
              }

              public Student find(String name)
              {
              Student found = null;

              for (Student student : students)
              {
              if (student.getName().equals(name))
              {
              found = student;
              break;
              }
              }

              return found;
              }
              }

              class Student
              {
              public static final DateFormat DATE_FORMATTER = new SimpleDateFormat("dd-MMM-yyyy");

              private String name;
              private Date birthDate;

              public Student(String name, Date birthDate)
              {
              if ((name == null) || ("".equals(name.trim())))
              throw new IllegalArgumentException("name cannot be blank or null");

              if (birthDate == null)
              throw new IllegalArgumentException("birth date cannot be null");

              this.name = name;
              this.birthDate = new Date(birthDate.getTime());
              }

              public String getName()
              {
              return name;
              }

              public Date getBirthDate()
              {
              return birthDate;
              }


              public String toString()
              {
              return "Student{" +
              "name='" + name + '\'' +
              ", birthDate=" + DATE_FORMATTER.format(birthDate) +
              '}';
              }
              }




              %
              • 4. Re: Searching an ArrayList of Student objects using a passed String?
                807606
                // List<Student> list
                Student result = list.get(list.indexOf(new Student(...)));
                • 5. Re: Searching an ArrayList of Student objects using a passed String?
                  807606
                  Thank you for the advice, but I don't believe that I am allowed to use a Map. I have an ArrayList named "students" that holds the Student objects that I create. Each Student object has a String field called "name", a double field called "gpa", and an ArrayList field called "courses" which holds the Course objects that I create(in other words, the courses that the student is enrolled in).

                  So when I input to the program:

                  add Bob cs101

                  I am calling an add() method that I created that is supposed to add the student (in this case, Bob) to the course (in this case, cs101). But I have to be able to search through the "students" ArrayList using only the string "Bob" in order to find the Student object with "Bob" as its "name" field (the "name" field is of type String). I need to do all this using only the constraints that I listed in my first post.

                  I should probably note that I am a student in a second level Java course, so I am not going to understand a wide variety of advanced Java techniques. Any more help would be greatly appreciated!
                  • 6. Re: Searching an ArrayList of Student objects using a passed String?
                    807606
                    Does listing in #3 not help you? It's quite self-explanatory and complete in itself.
                    • 7. Re: Searching an ArrayList of Student objects using a passed String?
                      796254
                      yes, look at the find method.

                      %
                      • 8. Re: Searching an ArrayList of Student objects using a passed String?
                        807606
                        Define
                        public boolean equals(Object o)
                        {
                          return o instanceof Student && this.getName().equals(((Student)o).getName());
                        }
                        in your Student class (and the method getName() if it is not defined already). Then use the method I gave you above to acquire a reference to the Student object that you want to add the course for (the indexOf() method compares the objects using equals()). Then just call
                        // Student student
                        student.addCourse(...);
                        provided addCourse(...) is defined in Student class.

                        Jukka
                        • 9. Re: Searching an ArrayList of Student objects using a passed String?
                          807606
                          I'm not quite sure if it does or not. Here is my Student class:
                          package cs201.lab3.jtc4z;
                          
                          import java.util.ArrayList;
                          
                          public class Student {
                               
                               // fields
                               private String name;
                               private double gpa;
                               private ArrayList courses;
                               
                               // getName(): accessor method for name field
                               public String getName() {
                                    return name;
                               }
                               
                               // getGPA(): accessor method for gpa field
                               public double getGPA() {
                                    return gpa;
                               }
                               
                               // setGPA(): mutator method for gpa field
                               public void setGPA(double gradePointAverage) {
                                    gpa = gradePointAverage;
                               }
                               
                               // getCourses(): accessor method for courses field
                               public ArrayList getCourses() {
                                    return courses;
                               }
                               
                               // add(): adds the passed course to the student's list of courses and adds
                               //        the student to the course's roll
                               public boolean add(Course aCourse) {
                                    if(courses.contains(aCourse)) {
                                         return false;
                                    }
                                    
                                    else {
                                         courses.add(aCourse);
                                         
                                         aCourse.getRoll().add(this);
                                    }
                                    
                                    return true;
                               }
                               
                               // drop(): drops the passed course from the student's list of courses and
                               //         drops the student from the course's roll
                               public boolean drop(Course aCourse) {
                                    if(!courses.contains(aCourse)) {
                                         return false;
                                    }
                                    
                                    else {
                                         int indexOfCourse = courses.indexOf(aCourse);
                                         
                                         courses.remove(indexOfCourse);
                                         
                                         aCourse.getRoll().remove(this);
                                    }
                                    
                                    return true;
                               }
                               
                               // dropAll(): drops all the student's courses and removes the student from
                               //            each course's roll
                               public void dropAll() {
                                    for(int i = 0; i < courses.size(); ++i) {
                                         Course aCourse = (Course) courses.get(i);
                                         
                                         aCourse.getRoll().remove(this);
                                    }
                                    
                                    courses.clear();
                               }
                               
                               // toString(): concatenates the student's information into one string
                               public String toString() {
                                    String info = "Name: " + getName() + " GPA: " + getGPA() +
                                                     " Course(s): " + courses.size();
                                    
                                    return info;
                               }
                               
                               // coursesAsString(): represents the student's courses as a string
                               public String coursesAsString() {
                                    return courses.toString();
                               }
                               
                               // equals(): checks to see if two students are equal to one another
                               public boolean equals(Object s2) {
                                    if(s2 instanceof Student) {
                                         Student student = (Student) s2;
                                    
                                         return student.getName().equals(getName());
                                    }
                                    
                                    return false;
                               }
                               
                               // Student(): specific constructor
                               public Student(String nameOfStudent, double gradePointAverage) {
                                    name = nameOfStudent;
                                    
                                    setGPA(gradePointAverage);
                                    
                                    courses = new ArrayList();
                               }
                               
                               // Student(): another specific constructor
                               public Student(String nameOfStudent) {
                                    name = nameOfStudent;
                                    
                                    setGPA(0.0);
                                    
                                    courses = new ArrayList();
                               }
                               
                          }
                          And here is my Course class:
                          package cs201.lab3.jtc4z;
                          
                          import java.util.ArrayList;
                          
                          public class Course {
                               
                               // fields
                               private String name;
                               private String id;
                               private ArrayList roll;
                               
                               // getName(): accessor method for name field
                               public String getName() {
                                    return name;
                               }
                               
                               // getID(): accessor method for id field
                               public String getID() {
                                    return id;
                               }
                               
                               // getRoll(): accessor method for roll field
                               public ArrayList getRoll() {
                                    return roll;
                               }
                               
                               // add(): adds the passed student to the course's roll and adds the course
                               //        to the student's list of courses
                               public boolean add(Student aStudent) {
                                    if(roll.contains(aStudent)) {
                                         return false;
                                    }
                                    
                                    else {
                                         roll.add(aStudent);
                                         
                                         aStudent.getCourses().add(this);
                                    }
                                    
                                    return true;
                               }
                               
                               // drop(): drops the passed student from the course's roll and drops the
                               //         course from the student's list of courses
                               public boolean drop(Student aStudent) {
                                    if(!roll.contains(aStudent)) {
                                         return false;
                                    }
                                    
                                    else {
                                         int indexOfStudent = roll.indexOf(aStudent);
                                         
                                         roll.remove(indexOfStudent);
                                         
                                         aStudent.getCourses().remove(this);
                                    }
                                    
                                    return true;
                               }
                               
                               // cancel(): drops all the course's students and removes the course from
                               //           each student's list of courses
                               public void cancel() {
                                    for(int i = 0; i < roll.size(); ++i) {
                                         Student aStudent = (Student) roll.get(i);
                                         
                                         aStudent.getCourses().remove(this);
                                    }
                                    
                                    roll.clear();
                               }
                               
                               // toString(): concatenates the course's information into one string
                               public String toString() {
                                    String info = "Name: " + getName() + " ID: " + getID() +
                                                     " Student(s): " + roll.size();
                                    
                                    return info;
                               }
                               
                               // rollAsString(): represents the course's roll as a string
                               public String rollAsString() {
                                    return roll.toString();
                               }
                               
                               // equals(): checks to see if two courses are equal to one another
                               public boolean equals(Object s2) {
                                    if(s2 instanceof Course) {
                                         Course course = (Course) s2;
                                    
                                         return course.getID().equals(getID());
                                    }
                                    
                                    return false;
                               }
                          
                               // Course(): specific constructor
                               public Course(String courseID, String nameOfCourse) {
                                    id = courseID;
                                    
                                    name = nameOfCourse;
                                    
                                    roll = new ArrayList();
                               }
                               
                          }
                          Finally, here is the class I am having the problem with, called HW1Shell:
                          package cs201.lab3.jtc4z;
                          
                          import java.util.ArrayList;
                          import java.util.Scanner;
                          
                          public class HW1Shell {
                               
                               private static ArrayList courses;
                               private static ArrayList students;
                               
                               private static boolean createStudent(String name, double gpa) {
                                    Student aStudent = new Student(name, gpa);
                                    
                                    students.add(aStudent);
                                    
                                    return true;
                               }
                               
                               private static boolean createCourse(String id, String name) {
                                    Course aCourse = new Course(id, name);
                                    
                                    courses.add(aCourse);
                                    
                                    return true;
                               }
                               
                               private static boolean addStudent(String name, String id) {
                                    
                               }
                               
                               private static boolean dropStudent(String name, String id) {
                                    
                               }
                               
                               private static boolean withdrawStudent(String name) {
                                    
                               }
                               
                               private static boolean cancelCourse(String id) {
                                    
                               }
                               
                               private static String listCourse(String id) {
                                    
                               }
                               
                               private static String listStudent(String name) {
                                    
                               }
                               
                               /**
                                * @param args
                                */
                               public static void main(String[] args) {
                                    // TODO Auto-generated method stub
                                    Scanner stdin = new Scanner(System.in);
                                    
                                    System.out.println("Please enter a command (enter \"exit\" when done): ");
                                    
                                    String command = stdin.nextLine();
                                    
                                    while(!command.equals("exit")) {
                                         String[] tokens = command.split("\\s+");
                                         
                                         if(tokens[0].equals("student")) {
                                              createStudent(tokens[1], Double.parseDouble(tokens[2]));
                                         }
                                         
                                         else if(tokens[0].equals("course")) {
                                              createCourse(tokens[1], tokens[2]);
                                         }
                                         
                                         else if(tokens[0].equals("add")) {
                                              addStudent(tokens[1], tokens[2]);
                                         }
                                         
                                         else if(tokens[0].equals("drop")) {
                                              dropStudent(tokens[1], tokens[2]);
                                         }
                                         
                                         else if(tokens[0].equals("withdraw")) {
                                              withdrawStudent(tokens[1]);
                                         }
                                         
                                         else if(tokens[0].equals("cancel")) {
                                              cancelCourse(tokens[1]);
                                         }
                                         
                                         else if(tokens[0].equals("listcourse")) {
                                              listCourse(tokens[1]);
                                         }
                                         
                                         else if(tokens[0].equals("liststudent")) {
                                              listStudent(tokens[1]);
                                         }
                                         
                                         else {
                                              System.out.println("!!! Incorrect command syntax. Please try again.\n");
                                         }
                                         
                                         System.out.println("Please enter a command (enter \"exit\" when done): ");
                                         
                                         command = stdin.nextLine();
                                    }
                               }
                          
                          }
                          Thanks again for any help!
                          • 10. Re: Searching an ArrayList of Student objects using a passed String?
                            807606
                            I would just like to point out that I can only make changes to the HW1Shell class because of the requirements placed on the project by my instructor. Thanks again!
                            • 11. Re: Searching an ArrayList of Student objects using a passed String?
                              807606
                              Now that you have your code, why don't you let us know what is working and what is not?

                              We don't entertain requests for testing your program.

                              Please test the same for yourself, and come back with what is not working as you're aware of what it is supposed to do.
                              • 12. Re: Searching an ArrayList of Student objects using a passed String?
                                807606
                                At the moment, both the createStudent() and createCourse() methods in the HW1Shell class don't seem to be working. I am getting a NullPointerException.

                                The createStudent() method is supposed to create a Student object and store it on the list of students (in HW1Shell).

                                The createCourse() method is supposed to create a Course object and store it on the list of courses (in HW1Shell).
                                • 13. Re: Searching an ArrayList of Student objects using a passed String?
                                  807606
                                  public class HW1Shell {
                                       
                                       private static ArrayList courses;
                                       private static ArrayList students;
                                       
                                  ArrayList instances courses and students are not initialised.

                                  Change these two lines as :
                                       private static ArrayList courses = new ArrayList();
                                        private static ArrayList students = new ArrayList();
                                  • 14. Re: Searching an ArrayList of Student objects using a passed String?
                                    807606
                                    The NullPointerException for the createStudent() method in HW1Shell looks like:

                                    Please enter a command (enter "exit" when done):
                                    student Bob 3.5
                                    Exception in thread "main" java.lang.NullPointerException
                                         at cs201.lab3.jtc4z.HW1Shell.createStudent(HW1Shell.java:14)
                                         at cs201.lab3.jtc4z.HW1Shell.main(HW1Shell.java:62)

                                    And the NPE for the createCourse() method in HW1Shell looks like:

                                    Please enter a command (enter "exit" when done):
                                    course cs101 intro-to-computer-science
                                    Exception in thread "main" java.lang.NullPointerException
                                         at cs201.lab3.jtc4z.HW1Shell.createCourse(HW1Shell.java:20)
                                         at cs201.lab3.jtc4z.HW1Shell.main(HW1Shell.java:66)

                                    Thanks to all who are trying to help me out here. I really appreciate it!
                                    1 2 Previous Next