A search method that finds a string value in an String Array

  • A+
Category:Languages

So I am trying to create a method that finds a title in a ArrayList of photos.

public class Album {      private String albumtitle;     private ArrayList<Photo> photos;      /**      * This constructor should initialize the      * instance variables of the class.      */     public Album(String title) {          this.albumtitle = title;         photos = new ArrayList<>();      } 

This is the code I have got to for trying to search for a specific title of the photo. I am not sure if i should put (int index) or (String title) in the methods parameters.

public Photo searchByTitle(int index) {          if (index >= 0 && index < photos.size()) {             String title = photos.get(index);             System.out.println(title);         }         return null;     } 

I am beginner programmer, and I feel a little guidance will help a lot.

Edit: So lots of people are telling me to use for loops. My project requires me to not do for loops for methods, hence why I have displayed it in this way.

I'll give you an example the lecturer gave us:

https://lms.uwa.edu.au/bbcswebdav/pid-1134902-dt-content-rid-16529804_1/courses/CITS1001_SEM-2_2018/lectures/BooksReadJournal.java.pdf

She doesn't use for loops.

 


You could use the stream-API:

Arrays.stream(photos).filter(p -> p.getTitle().equalsIgnoreCase(searchTitle)).findFirst().orElseGet(...); 

You iterate over each photo called p in this array and compare p's title with the one you search and return the first match.

Or simply use a normal for-loop:

for(int i = 0; i < photos.size(); i++) {   if(photos[i].getTitle().equalsIgnoreCase(searchTitle)){ return photos[i]; }   return new ErrorPhoto(); //or some error state } 

More enhanced for-each-loop:

for(Photo p: photos) {   if(p.getTitle().equalsIgnoreCase(searchTitle)) { return p; }   return new ErrorPhoto(); //or some error state } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: