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
}
You iterate over each photo and compare its title with the one you search and return the first match:
for(int i = 0; i < photos.size, i++) {
if(photos.get(i).getTile().equals("title name"){
System.out.println("Found the title");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With