I need some help with a homework question I am working on. I need to create a “Library” class that contains an array of Song objects.(capacity of 10). Then make a method addSong. Here’s what I have so far:
public class Library{ Song[] arr = new Song[10]; public void addSong(Song s){ for(int i=0; i<10; i++) arr[i] = s; } }
My question is: Is there another way to fill the array? i will later need to search for a song based on a index value. So i will create a method like: public Song getSong(int idx) Thank you in anticipation for your answers!
Answer
If you really have to use an array (and not an ArrayList or LinkedList), this solution may be the right for you:
public class Library{ private Song[] arr = new Song[10]; private int songNumber = 0; //the number of Songs already stored in your array public void addSong(Song s){ arr[songNumber++] = s; } }
If you want to avoid a runtime-exeption if you add more then 10 songs:
public void addSong(Song s){ if(songNumber<10) { arr[songNumber++] = s; }else{ //what to do if more then 10 songs are added } }