Hello there,
I am working on an assignment for school and I am having a hard time understanding the concept of an array of objects. I am required to create an array of Music objects so that I can search through them via a binary search and make changes as stipulated by reading a .txt file.
My problem is, I do not think I understand Object arrays properly. I can not seem to populate the array from the Music class. Do I populate in the instanceOf if block? Does it matter? I have two test populations of the array under the music instance of RockSong block and on trying to System.out.println() the output for accuracy I just get a null result. Any shove in the right direction would be most appreciated. Thank you.
public class Main
{
private TextFileReader listenFile;
private ListenFile currentRecord, nextRecord;
private Music music;
String listenDate = "";
String listenName = "";
String musicType ="";
String rockGroup = "";
String musicName = "";
Calendar date;
Calendar closeDate;
Date df;
public static void main (String args[])
{
(new Main()).DisplayFile();
}
private void DisplayFile()
{
int count =0;
ObjectInputStream inFile = null;
try
{ inFile = new ObjectInputStream (new FileInputStream("music.dat"));}
catch (IOException ioex) { System.out.println ("ERROR Opening"); System.exit(1); }
try
{
while (true)
{
Music music = (Music)inFile.readObject();
Music[] musicArray= new Music[300];
if (music instanceof RockSong){
musicArray[0].name = music.name;
muiscArray[1].timesPlayed = music.timesPlayed;
}
if (music instanceof ClassicalPiece){
}
if (music instanceof Musical){
closeDate = (((Musical)music).close);
if (closeDate == null) {
((Musical)music).close=Calendar.getInstance();
}
}
System.out.println(musicArray[count]);
count++;
}
}
catch (EOFException eofex) { System.out.println ("\nDONE");}
catch (IOException ioex) { System.out.println ("ERROR Reading"); System.exit(1); }
catch (ClassNotFoundException cnfex) { System.out.println ("ERROR class"); System.exit(1); }
}
And here are my classes:
class Music implements Serializable
{
String name;
int timesPlayed;
Calendar lastTime;
}
class RockSong extends Music
{
String group;
}
class ClassicalPiece extends Music
{
String composer;
String type;
}
class Musical extends Music
{
Calendar open;
Calendar close;
}