简体   繁体   中英

Searching through an object ArrayList

public class favoriteshow {

String name = null; 
int age = 0; 
String show = null; 

public Lab2(String name, int age, String show){
    this.name = name; 
    this.age = age; 
    this.show = show; 
}

public String toString(){
    return "Name " + name + " age: " + age + " Favorite show: " + show; 
}

}

My main class:

public class NewClass {
public static void main(String args[]){
    int x = 0;

    ArrayList<favoriteshow> arraylist = new ArrayList<favoriteshow>();

 while( x < 5){ 
    String name;
    int age = 0;
    String show;

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a name: ");
    name = scanner.nextLine();

    System.out.print("Enter an age: ");
    age = scanner.nextInt();

    System.out.print("Enter a show: ");
    show = scanner.nextLine();

    Lab2 nub1 = new Lab2 (name, age , show); 




    arraylist.add(nub1);
      x++;

    }

   System.out.println(arraylist);


 }
}

(I know my while loop only repeats 5 times because I was just testing it.)

So I have an arraylist that a user types in a person name, age, and favorite show. I want to include a search function so, if i was to ask the user to type in a name it will show the information for ALL of the people that have that same name, not just the first person. I also want it to tell me what number on the list that person is. For example, if i was to have 5 people and 2 of them had the same name, and they were the 2 and 4 position then it will tell me that they are the second and forth position.

Just iterate through the ArrayList indexes as in a normal array and make the comparison with the desired field, eg:

public void searchAndShow(String name) {
    for (int i = 0; i < arraylist.size(); i++) {
        favoriteshow fs = arraylist.get(i);
        if (fs.getName().equals(name)) {
            System.out.println(i + " - " + fs);
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM