I'm currently a bit stuck with part of an assignment and was hoping you might be able to show me where I'm going wrong.
I'm building an unsophisticated iTunes program and currently working on a method to get all the musicians involved with a particular track and display them as a string (eg "Frank Black, Joey Santiago, Kim Deal" etc.) This method needs to work by retrieving an array list inside the Artist object and displaying it.
I'm having trouble with my get()
method though. I know that I should implement a get()
method so that the Track object can access fields in the Artist object, but all the ways I've tried to do this have sent up error messages. So far, I've tried an enhanced 'for loop' like this:
for (String member : members.getMembers() ) {
where 'members' is an ArrayList
which contains a String
for each of the musician's names, but that sends up "cannot find symbol - variable members". Then I tried this:
for (String member : Artist.members.getMembers() ) {
but that says "non-static variable members cannot be referenced from a static context". I get the feeling I'm missing something pretty basic here. Do any of you have any idea what it might be...?
If members is an arrayList holding strings, then you should do like this
for (String m: members){
}
Or
for (String m : Artist.members){
}
which ever is applicable to your situition
Here Artist
is a class and not an instance of a class. Generally an Artist does not have any member, whereas John Doe especially, can have a list of members.
You need to get an Artist instance in order to ask for his members
Supposing that each Track
has one Artist
, and each Artist
may have multiple musicians (members), then you are looking for something like this:
public class Artist {
private List<String> members;
// ...
public List<String> getMembers() {
return Collections.unmodifiableList(members);
}
}
public class Track {
private Artist artist;
// ...
public String getMusicians() {
StringBuilder sb = new StringBuilder();
int length;
for (String member : artist.getMembers()) {
sb.append(member).append(", ");
}
return sb.substring(0, sb.length() - 2);
}
}
First you would need to instantiate an Artist
object, then iterate over the ArrayList<String>
containing the artists.
class Artist {
private List<String> artists;
...
public List<String> getArtists() {
return artists;
}
...
}
then when you want to iterate over it
public static void main(String[] args) { //or where ever you call it from
members = new Artist();
// do stuff to members object
for (String m : members.getArtists())
System.out.print(m + " ");
System.out.println();
}
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.