0

Let say I have an ArrayList<Student> contains 4 Students(name , city, school). For example:

 1. John   Nevada   BBBB
 2. Mary   Ander    AAAA
 3. Winn   Arcata   CCCC
 4. Ty     Artes    BBBB

If user enter “BBBB” then it displays: :

 1. John    Nevada   BBBB
 2. Ty      Artes    BBBB

My question is that how do I compare a input string “BBBB” with the schools in the above ArrayList? Thank you for any help that you guys would provide!

public class Student
{
    private String name;
    private String city;
    private String school;

    /**
     * Constructor for objects of class Student
     */
    public Student(String name, String city, String school)
    {
       this.name = name;
       this.city = city;
       this.school = school;
    }

    public String getSchool(String school)
    {
        return this.school = school;
    }

     public String toString()
    {
        return  "Name: " + name + "\tCity: " +city+ "\tSchool: "+school;
    }


}


public class AllStudent
{
    // instance variables - replace the example below with your own
    private ArrayList<Student> listStudent = new ArrayList<Student>();

    /**
     * Constructor for objects of class AllStudent
     */
    public AllStudent() throws IOException
    {

        //variables
        // read an input file and save it as an Arraylist
        fileScan = new Scanner (new File("students.txt");
        while(fileScan.hasNext())
        {
            //.......
            listStudent.add(new Student(name,city,school);
     }
     //now let user enter a school, the display name, city, school of that student.
     //i am expecting something like below...
     public void displayStudentBasedOnSchool(String school)
     {
       for (i = 0; i < listStudent.size(); i++)
       {
        //what should i put i here to comapre in input School with school in the listStudent>
        }
     }
}
Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
user2774903
  • 325
  • 3
  • 6
  • We would have to see your code; you likely just have to modify one thing (make something like a `searchByCity(String s)` function). – Chris Forrence Sep 13 '13 at 03:16
  • You may need to override `compare` method to define compare logic in Student class – Deepak Ingole Sep 13 '13 at 03:18
  • Start by posting your `Student` class and how you declare and use your `ArrayList`. – Sotirios Delimanolis Sep 13 '13 at 03:21
  • How are you students stored? An object, a string of the format above? Are those numbers an index in the `ArrayList`? @captain I suspect I would recommend against that. Chances are that a Student's `compare` method shouldn't be based only on the school. – jpmc26 Sep 13 '13 at 03:22

3 Answers3

2

Assuming your student is modelled like this (AAAA, BBBB values are stored in blah field):

public class Student {

  private String name;
  private String state;
  private String blah;

  //getters & setters..

}

The simplest (not most efficient way) is just to loop the array list and compare the query string with value of blah field

for(Student s : studentList) {
  if(s.getBlah().equals(queryString)) {
    // match!..
  }
}
gerrytan
  • 40,313
  • 9
  • 84
  • 99
  • acctually, it is an arrayList – user2774903 Sep 13 '13 at 03:33
  • acctually, it is an arrayList of student, and each student has three parameter including name, city, school. for example if I loop throgh the arraylist public void displayStudentBasedOnSchool(String BBBB) { for(int i = 0; i < studentList.size(); i ++) { //how do i campare the input "BBBB" with parameter school in this studentList? } } – user2774903 Sep 13 '13 at 03:44
  • 2
    `for(Student s : studentList)` is an 'syntax sugar' for `for(int i=0; i < studentList.size(); i++) { Student s = studentList.get(i); ...` – gerrytan Sep 13 '13 at 04:21
  • can i use s.contains(comparedSchool)? after set it up each s = studentList.get(i)? – user2774903 Sep 13 '13 at 04:46
  • @gerrytan Strictly speaking, the `for`-each construct uses an iterator unless the collection is an array. (See [here](http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work).) That means it works on any `Iterable` and will be reasonably efficient with other constructs like `LinkedList`. – jpmc26 Oct 10 '13 at 22:52
1

I believe Student is class and you are creating list of Student

The ArrayList uses the equals method implemented in the class (your case Student class) to do the equals comparison.

You can call contains methods of list to get matching object

Like,

public class Student {
  private String name;
  private String city;
  private String school;
  ....   

  public Student(String name, String city, String school) {
      this.name = name;
      this.city = city;
      this.school = school;
  }

   //getters & setters..
  public String setSchool(String school) {
      this.school = school;
  }

  public String getSchool() {
      return this.school;
  }

  public boolean equals(Object other) {
      if (other == null) return false;
      if (other == this) return true;

      if (!(other instanceof Student)) return false;
      Student s = (Student)other;

      if (s.getSchool().equals(this.getSchool())) {
          return true; // here you compare school name
      } 
      return false;
  }

  public String toString() {
      return  "Name: " + this.name + "\tCity: " + this.city + "\tSchool: "+ this.school;
  }
}

Your array list would be like this

ArrayList<Student> studentList = new ArrayList<Student>();  

Student s1 = new Student(x, y, z);
Student s2 = new Student(a, b, c);  

studentList.add(s1);
studentList.add(s2);

Student s3 = new Student(x, y, z); //object to search

if(studentList.contains(s3)) {
    System.out.println(s3.toString()); //print object if object exists;
} // check if `studentList` contains `student3` with city `y`.It will internally call your equals method to compare items in list.

Or,

You can simply iterate object in studentList and compare items

for(Student s : studentList) {
  if(s.getSchool().equals(schoolToSearch)) {
    // print object here!..

  }
}

Or, as you commented ,

public void displayStudentBasedOnSchool(String school){
    for(int i = 0; i < studentList.size(); ++i) {
        if(studentList.get(i).getSchool().equals(school)) {
            System.out.println(studentList.get(i).toString()); // here studentList.get(i) returns Student Object.
        }
    }
}

Or,

ListIterator<Student> listIterator = studentList.listIterator(); //use list Iterator

while(listIterator.hasNext()) {
    if(iterator.next().getSchool().equals(school)) {
        System.out.println(listIterator.next());
        break;
    }
}

or even,

int j = 0;
while (studentList.size() > j) {
    if(studentList.get(j).getSchool().equals(school)){
        System.out.println(studentList.get(j));
        break;
    }
    j++;
}

So now you have set of options

  1. for-loop
  2. for-each loop
  3. while loop
  4. iterator
Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
  • yes, I have been working on your feedback. I tried to fix my code with your answer to match my need, but it still does not work.The error message was: "array required, but java.util.ArrayList found". – user2774903 Sep 13 '13 at 05:17
  • dont be sorry,that was what I figured too.I actually had came up with your last code before I posted this problem, but it still does not work. the error message was: "method getSchool in class Student cannot be applied to given types. require:java.lang.String; found: no arguments; reason: actual or formal argument lists differ in length. – user2774903 Sep 13 '13 at 07:02
  • public class Student { private String name; private String city; private String school; /** * Constructor for objects of class Student */ public Student(String name, String city, String school) { this.name = name; this.city = city; this.school = school; } public String getSchool(String school) { return this.school = school; } public String toString() { return "Name: " + name + "\tCity: " +city+ "\tSchool: "+school; } } – user2774903 Sep 13 '13 at 07:12
  • I still get the same error as I indicated above "mothod getSchool......". Thanks for being so helpfull. – user2774903 Sep 13 '13 at 07:25
  • I totally understand. Maybe I need to play around with it little more. I will let you know when it finally works. – user2774903 Sep 13 '13 at 07:32
  • 1
    AAAAAAAAAAA my program works perfectly now. I have learned a lot. Thank you so much guys, . you guys are amazing :D. Special thank you to CAPTAIN! – user2774903 Sep 14 '13 at 01:10
0

I would probably use Guava library from Google.
Take a look at this question: What is the best way to filter a Java Collection? It provides many excelent solutions for your problem.

Community
  • 1
  • 1
Ondrej Bozek
  • 10,987
  • 7
  • 54
  • 70
  • Let him understand java's capability/features first.Its not preferred to switch over library for such a ant size code when java can do it – Deepak Ingole Sep 13 '13 at 08:44